Whamcloud - gitweb
LU-10551 lod: obd_fid_alloc() could start a nested trans
[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  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/osd/osd_handler.c
33  *
34  * Top-level entry points into osd module
35  *
36  * Author: Nikita Danilov <nikita@clusterfs.com>
37  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
38  */
39
40 #define DEBUG_SUBSYSTEM S_OSD
41
42 #include <linux/kallsyms.h>
43 #include <linux/module.h>
44 #include <linux/user_namespace.h>
45 #ifdef HAVE_UIDGID_HEADER
46 # include <linux/uidgid.h>
47 #endif
48
49 /* prerequisite for linux/xattr.h */
50 #include <linux/types.h>
51 /* prerequisite for linux/xattr.h */
52 #include <linux/fs.h>
53 /* XATTR_{REPLACE,CREATE} */
54 #include <linux/xattr.h>
55
56 #include <ldiskfs/ldiskfs.h>
57 #include <ldiskfs/xattr.h>
58 #include <ldiskfs/ldiskfs_extents.h>
59 #undef ENTRY
60 /*
61  * struct OBD_{ALLOC,FREE}*()
62  * OBD_FAIL_CHECK
63  */
64 #include <obd_support.h>
65 /* struct ptlrpc_thread */
66 #include <lustre_net.h>
67 #include <lustre_fid.h>
68 /* process_config */
69 #include <uapi/linux/lustre/lustre_param.h>
70
71 #include "osd_internal.h"
72 #include "osd_dynlocks.h"
73
74 /* llo_* api support */
75 #include <md_object.h>
76 #include <lustre_quota.h>
77
78 #include <lustre_linkea.h>
79
80 /* Maximum EA size is limited by LNET_MTU for remote objects */
81 #define OSD_MAX_EA_SIZE 1048364
82
83 int ldiskfs_pdo = 1;
84 module_param(ldiskfs_pdo, int, 0644);
85 MODULE_PARM_DESC(ldiskfs_pdo, "ldiskfs with parallel directory operations");
86
87 int ldiskfs_track_declares_assert;
88 module_param(ldiskfs_track_declares_assert, int, 0644);
89 MODULE_PARM_DESC(ldiskfs_track_declares_assert, "LBUG during tracking of declares");
90
91 /* Slab to allocate dynlocks */
92 struct kmem_cache *dynlock_cachep;
93
94 /* Slab to allocate osd_it_ea */
95 struct kmem_cache *osd_itea_cachep;
96
97 static struct lu_kmem_descr ldiskfs_caches[] = {
98         {
99                 .ckd_cache = &dynlock_cachep,
100                 .ckd_name  = "dynlock_cache",
101                 .ckd_size  = sizeof(struct dynlock_handle)
102         },
103         {
104                 .ckd_cache = &osd_itea_cachep,
105                 .ckd_name  = "osd_itea_cache",
106                 .ckd_size  = sizeof(struct osd_it_ea)
107         },
108         {
109                 .ckd_cache = NULL
110         }
111 };
112
113 static const char dot[] = ".";
114 static const char dotdot[] = "..";
115
116 static const struct lu_object_operations      osd_lu_obj_ops;
117 static const struct dt_object_operations      osd_obj_ops;
118 static const struct dt_object_operations      osd_obj_otable_it_ops;
119 static const struct dt_index_operations       osd_index_iam_ops;
120 static const struct dt_index_operations       osd_index_ea_ops;
121
122 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
123                           const struct lu_fid *fid);
124 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
125                                                 struct osd_device *osd);
126
127 int osd_trans_declare_op2rb[] = {
128         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
129         [OSD_OT_PUNCH]          = OSD_OT_MAX,
130         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
131         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
132         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
133         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
134         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
135         [OSD_OT_WRITE]          = OSD_OT_WRITE,
136         [OSD_OT_INSERT]         = OSD_OT_DELETE,
137         [OSD_OT_DELETE]         = OSD_OT_INSERT,
138         [OSD_OT_QUOTA]          = OSD_OT_MAX,
139 };
140
141 static int osd_has_index(const struct osd_object *obj)
142 {
143         return obj->oo_dt.do_index_ops != NULL;
144 }
145
146 static int osd_object_invariant(const struct lu_object *l)
147 {
148         return osd_invariant(osd_obj(l));
149 }
150
151 /*
152  * Concurrency: doesn't matter
153  */
154 static int osd_is_write_locked(const struct lu_env *env, struct osd_object *o)
155 {
156         struct osd_thread_info *oti = osd_oti_get(env);
157         return oti->oti_w_locks > 0 && o->oo_owner == env;
158 }
159
160 /*
161  * Concurrency: doesn't access mutable data
162  */
163 static int osd_root_get(const struct lu_env *env,
164                         struct dt_device *dev, struct lu_fid *f)
165 {
166         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
167         return 0;
168 }
169
170 /*
171  * the following set of functions are used to maintain per-thread
172  * cache of FID->ino mapping. this mechanism is needed to resolve
173  * FID to inode at dt_insert() which in turn stores ino in the
174  * directory entries to keep ldiskfs compatible with ext[34].
175  * due to locking-originated restrictions we can't lookup ino
176  * using LU cache (deadlock is possible). lookup using OI is quite
177  * expensive. so instead we maintain this cache and methods like
178  * dt_create() fill it. so in the majority of cases dt_insert() is
179  * able to find needed mapping in lockless manner.
180  */
181 static struct osd_idmap_cache *
182 osd_idc_find(const struct lu_env *env, struct osd_device *osd,
183              const struct lu_fid *fid)
184 {
185         struct osd_thread_info  *oti   = osd_oti_get(env);
186         struct osd_idmap_cache  *idc    = oti->oti_ins_cache;
187         int i;
188         for (i = 0; i < oti->oti_ins_cache_used; i++) {
189                 if (!lu_fid_eq(&idc[i].oic_fid, fid))
190                         continue;
191                 if (idc[i].oic_dev != osd)
192                         continue;
193
194                 return idc + i;
195         }
196
197         return NULL;
198 }
199
200 static struct osd_idmap_cache *
201 osd_idc_add(const struct lu_env *env, struct osd_device *osd,
202             const struct lu_fid *fid)
203 {
204         struct osd_thread_info  *oti   = osd_oti_get(env);
205         struct osd_idmap_cache  *idc;
206         int i;
207
208         if (unlikely(oti->oti_ins_cache_used >= oti->oti_ins_cache_size)) {
209                 i = oti->oti_ins_cache_size * 2;
210                 if (i == 0)
211                         i = OSD_INS_CACHE_SIZE;
212                 OBD_ALLOC(idc, sizeof(*idc) * i);
213                 if (idc == NULL)
214                         return ERR_PTR(-ENOMEM);
215                 if (oti->oti_ins_cache != NULL) {
216                         memcpy(idc, oti->oti_ins_cache,
217                                oti->oti_ins_cache_used * sizeof(*idc));
218                         OBD_FREE(oti->oti_ins_cache,
219                                  oti->oti_ins_cache_used * sizeof(*idc));
220                 }
221                 oti->oti_ins_cache = idc;
222                 oti->oti_ins_cache_size = i;
223         }
224
225         idc = oti->oti_ins_cache + oti->oti_ins_cache_used++;
226         idc->oic_fid = *fid;
227         idc->oic_dev = osd;
228         idc->oic_lid.oii_ino = 0;
229         idc->oic_lid.oii_gen = 0;
230         idc->oic_remote = 0;
231
232         return idc;
233 }
234
235 /*
236  * lookup mapping for the given fid in the cache, initialize a
237  * new one if not found. the initialization checks whether the
238  * object is local or remote. for local objects, OI is used to
239  * learn ino/generation. the function is used when the caller
240  * has no information about the object, e.g. at dt_insert().
241  */
242 static struct osd_idmap_cache *
243 osd_idc_find_or_init(const struct lu_env *env, struct osd_device *osd,
244                      const struct lu_fid *fid)
245 {
246         struct osd_idmap_cache *idc;
247         int rc;
248
249         idc = osd_idc_find(env, osd, fid);
250         LASSERT(!IS_ERR(idc));
251         if (idc != NULL)
252                 return idc;
253
254         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
255                osd->od_svname, PFID(fid));
256
257         /* new mapping is needed */
258         idc = osd_idc_add(env, osd, fid);
259         if (IS_ERR(idc)) {
260                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
261                        osd->od_svname, PFID(fid), PTR_ERR(idc));
262                 return idc;
263         }
264
265         /* initialize it */
266         rc = osd_remote_fid(env, osd, fid);
267         if (unlikely(rc < 0))
268                 return ERR_PTR(rc);
269
270         if (rc == 0) {
271                 /* the object is local, lookup in OI */
272                 /* XXX: probably cheaper to lookup in LU first? */
273                 rc = osd_oi_lookup(osd_oti_get(env), osd, fid,
274                                    &idc->oic_lid, 0);
275                 if (unlikely(rc < 0)) {
276                         CERROR("can't lookup: rc = %d\n", rc);
277                         return ERR_PTR(rc);
278                 }
279         } else {
280                 /* the object is remote */
281                 idc->oic_remote = 1;
282         }
283
284         return idc;
285 }
286
287 /*
288  * lookup mapping for given FID and fill it from the given object.
289  * the object is lolcal by definition.
290  */
291 static int osd_idc_find_and_init(const struct lu_env *env,
292                                  struct osd_device *osd,
293                                  struct osd_object *obj)
294 {
295         const struct lu_fid     *fid = lu_object_fid(&obj->oo_dt.do_lu);
296         struct osd_idmap_cache  *idc;
297
298         idc = osd_idc_find(env, osd, fid);
299         LASSERT(!IS_ERR(idc));
300         if (idc != NULL) {
301                 if (obj->oo_inode == NULL)
302                         return 0;
303                 if (idc->oic_lid.oii_ino != obj->oo_inode->i_ino) {
304                         LASSERT(idc->oic_lid.oii_ino == 0);
305                         idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
306                         idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
307                 }
308                 return 0;
309         }
310
311         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
312                osd->od_svname, PFID(fid));
313
314         /* new mapping is needed */
315         idc = osd_idc_add(env, osd, fid);
316         if (IS_ERR(idc)) {
317                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
318                        osd->od_svname, PFID(fid), PTR_ERR(idc));
319                 return PTR_ERR(idc);
320         }
321
322         if (obj->oo_inode != NULL) {
323                 idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
324                 idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
325         }
326         return 0;
327 }
328
329 /*
330  * OSD object methods.
331  */
332
333 /*
334  * Concurrency: no concurrent access is possible that early in object
335  * life-cycle.
336  */
337 static struct lu_object *osd_object_alloc(const struct lu_env *env,
338                                           const struct lu_object_header *hdr,
339                                           struct lu_device *d)
340 {
341         struct osd_object *mo;
342
343         OBD_ALLOC_PTR(mo);
344         if (mo != NULL) {
345                 struct lu_object *l;
346                 struct lu_object_header *h;
347                 struct osd_device *o = osd_dev(d);
348
349                 l = &mo->oo_dt.do_lu;
350                 if (unlikely(o->od_in_init)) {
351                         OBD_ALLOC_PTR(h);
352                         if (!h) {
353                                 OBD_FREE_PTR(mo);
354                                 return NULL;
355                         }
356
357                         lu_object_header_init(h);
358                         lu_object_init(l, h, d);
359                         lu_object_add_top(h, l);
360                         mo->oo_header = h;
361                 } else {
362                         dt_object_init(&mo->oo_dt, NULL, d);
363                         mo->oo_header = NULL;
364                 }
365
366                 mo->oo_dt.do_ops = &osd_obj_ops;
367                 l->lo_ops = &osd_lu_obj_ops;
368                 init_rwsem(&mo->oo_sem);
369                 init_rwsem(&mo->oo_ext_idx_sem);
370                 spin_lock_init(&mo->oo_guard);
371                 INIT_LIST_HEAD(&mo->oo_xattr_list);
372                 return l;
373         } else {
374                 return NULL;
375         }
376 }
377
378 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
379                 struct dentry *dentry, struct lustre_ost_attrs *loa)
380 {
381         int rc;
382
383         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
384                              (void *)loa, sizeof(*loa));
385         if (rc > 0) {
386                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
387
388                 if (rc < sizeof(*lma))
389                         return -EINVAL;
390
391                 rc = 0;
392                 lustre_loa_swab(loa, true);
393                 /* Check LMA compatibility */
394                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
395                         CWARN("%s: unsupported incompat LMA feature(s) %#x "
396                               "for fid = "DFID", ino = %lu\n",
397                               osd_ino2name(inode),
398                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
399                               PFID(&lma->lma_self_fid), inode->i_ino);
400                         rc = -EOPNOTSUPP;
401                 }
402         } else if (rc == 0) {
403                 rc = -ENODATA;
404         }
405
406         return rc;
407 }
408
409 /*
410  * retrieve object from backend ext fs.
411  **/
412 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
413                        struct osd_inode_id *id)
414 {
415         int rc;
416         struct inode *inode = NULL;
417
418         /* if we look for an inode withing a running
419          * transaction, then we risk to deadlock */
420         /* osd_dirent_check_repair() breaks this */
421         /*LASSERT(current->journal_info == NULL);*/
422
423         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
424         if (IS_ERR(inode)) {
425                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
426                        id->oii_ino, PTR_ERR(inode));
427         } else if (id->oii_gen != OSD_OII_NOGEN &&
428                    inode->i_generation != id->oii_gen) {
429                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
430                        "i_generation = %u\n",
431                        id->oii_ino, id->oii_gen, inode->i_generation);
432                 iput(inode);
433                 inode = ERR_PTR(-ESTALE);
434         } else if (inode->i_nlink == 0) {
435                 /* due to parallel readdir and unlink,
436                 * we can have dead inode here. */
437                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
438                 iput(inode);
439                 inode = ERR_PTR(-ESTALE);
440         } else if (is_bad_inode(inode)) {
441                 CWARN("%s: bad inode: ino = %u\n",
442                 osd_dev2name(dev), id->oii_ino);
443                 iput(inode);
444                 inode = ERR_PTR(-ENOENT);
445         } else if ((rc = osd_attach_jinode(inode))) {
446                 iput(inode);
447                 inode = ERR_PTR(rc);
448         } else {
449                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
450                 if (id->oii_gen == OSD_OII_NOGEN)
451                         osd_id_gen(id, inode->i_ino, inode->i_generation);
452
453                 /* Do not update file c/mtime in ldiskfs.
454                  * NB: we don't have any lock to protect this because we don't
455                  * have reference on osd_object now, but contention with
456                  * another lookup + attr_set can't happen in the tiny window
457                  * between if (...) and set S_NOCMTIME. */
458                 if (!(inode->i_flags & S_NOCMTIME))
459                         inode->i_flags |= S_NOCMTIME;
460         }
461         return inode;
462 }
463
464 int osd_ldiskfs_add_entry(struct osd_thread_info *info, struct osd_device *osd,
465                           handle_t *handle, struct dentry *child,
466                           struct inode *inode, struct htree_lock *hlock)
467 {
468         int rc, rc2;
469
470         rc = __ldiskfs_add_entry(handle, child, inode, hlock);
471         if (rc == -ENOBUFS || rc == -ENOSPC) {
472                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
473                 struct inode *parent = child->d_parent->d_inode;
474                 struct lu_fid *fid = NULL;
475
476                 rc2 = osd_get_lma(info, parent, child->d_parent, loa);
477                 if (!rc2) {
478                         fid = &loa->loa_lma.lma_self_fid;
479                 } else if (rc2 == -ENODATA) {
480                         if (unlikely(parent == inode->i_sb->s_root->d_inode)) {
481                                 fid = &info->oti_fid3;
482                                 lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
483                         } else if (!osd->od_is_ost && osd->od_index == 0) {
484                                 fid = &info->oti_fid3;
485                                 lu_igif_build(fid, parent->i_ino,
486                                               parent->i_generation);
487                         }
488                 }
489
490                 if (fid != NULL)
491                         CWARN("%s: directory (inode: %lu, FID: "DFID") %s "
492                               "maximum entry limit\n",
493                               osd_name(osd), parent->i_ino, PFID(fid),
494                               rc == -ENOSPC ? "has reached" : "is approaching");
495                 else
496                         CWARN("%s: directory (inode: %lu, FID: unknown) %s "
497                               "maximum entry limit\n",
498                               osd_name(osd), parent->i_ino,
499                               rc == -ENOSPC ? "has reached" : "is approaching");
500
501                 /* ignore such error now */
502                 if (rc == -ENOBUFS)
503                         rc = 0;
504         }
505
506         return rc;
507 }
508
509
510 struct inode *
511 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
512              struct osd_inode_id *id, struct lu_fid *fid)
513 {
514         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
515         struct inode *inode;
516         int rc;
517
518         inode = osd_iget(info, dev, id);
519         if (IS_ERR(inode))
520                 return inode;
521
522         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
523         if (!rc) {
524                 *fid = loa->loa_lma.lma_self_fid;
525         } else if (rc == -ENODATA) {
526                 if (unlikely(inode == osd_sb(dev)->s_root->d_inode))
527                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
528                 else
529                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
530         } else {
531                 iput(inode);
532                 inode = ERR_PTR(rc);
533         }
534         return inode;
535 }
536
537 static struct inode *osd_iget_check(struct osd_thread_info *info,
538                                     struct osd_device *dev,
539                                     const struct lu_fid *fid,
540                                     struct osd_inode_id *id,
541                                     bool trusted)
542 {
543         struct inode *inode;
544         int rc = 0;
545         ENTRY;
546
547         /* The cached OI mapping is trustable. If we cannot locate the inode
548          * via the cached OI mapping, then return the failure to the caller
549          * directly without further OI checking. */
550
551 again:
552         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
553         if (IS_ERR(inode)) {
554                 rc = PTR_ERR(inode);
555                 if (!trusted && (rc == -ENOENT || rc == -ESTALE))
556                         goto check_oi;
557
558                 CDEBUG(D_INODE, "no inode for FID: "DFID", ino = %u, rc = %d\n",
559                        PFID(fid), id->oii_ino, rc);
560                 GOTO(put, rc);
561         }
562
563         if (is_bad_inode(inode)) {
564                 rc = -ENOENT;
565                 if (!trusted)
566                         goto check_oi;
567
568                 CDEBUG(D_INODE, "bad inode for FID: "DFID", ino = %u\n",
569                        PFID(fid), id->oii_ino);
570                 GOTO(put, rc);
571         }
572
573         if (id->oii_gen != OSD_OII_NOGEN &&
574             inode->i_generation != id->oii_gen) {
575                 rc = -ESTALE;
576                 if (!trusted)
577                         goto check_oi;
578
579                 CDEBUG(D_INODE, "unmatched inode for FID: "DFID", ino = %u, "
580                        "oii_gen = %u, i_generation = %u\n", PFID(fid),
581                        id->oii_ino, id->oii_gen, inode->i_generation);
582                 GOTO(put, rc);
583         }
584
585         if (inode->i_nlink == 0) {
586                 rc = -ENOENT;
587                 if (!trusted)
588                         goto check_oi;
589
590                 CDEBUG(D_INODE, "stale inode for FID: "DFID", ino = %u\n",
591                        PFID(fid), id->oii_ino);
592                 GOTO(put, rc);
593         }
594
595         ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
596
597 check_oi:
598         if (rc != 0) {
599                 __u32 saved_ino = id->oii_ino;
600                 __u32 saved_gen = id->oii_gen;
601
602                 LASSERT(!trusted);
603                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
604
605                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
606                 /* XXX: There are four possible cases:
607                  *      1. rc = 0.
608                  *         Backup/restore caused the OI invalid.
609                  *      2. rc = 0.
610                  *         Someone unlinked the object but NOT removed
611                  *         the OI mapping, such as mount target device
612                  *         as ldiskfs, and modify something directly.
613                  *      3. rc = -ENOENT.
614                  *         Someone just removed the object between the
615                  *         former oi_lookup and the iget. It is normal.
616                  *      4. Other failure cases.
617                  *
618                  *      Generally, when the device is mounted, it will
619                  *      auto check whether the system is restored from
620                  *      file-level backup or not. We trust such detect
621                  *      to distinguish the 1st case from the 2nd case:
622                  *      if the OI files are consistent but may contain
623                  *      stale OI mappings because of case 2, if iget()
624                  *      returns -ENOENT or -ESTALE, then it should be
625                  *      the case 2. */
626                 if (rc != 0)
627                         /* If the OI mapping was in OI file before the
628                          * osd_iget_check(), but now, it is disappear,
629                          * then it must be removed by race. That is a
630                          * normal race case. */
631                         GOTO(put, rc);
632
633                 /* It is the OI scrub updated the OI mapping by race.
634                  * The new OI mapping must be valid. */
635                 if (saved_ino != id->oii_ino ||
636                     (saved_gen != id->oii_gen && saved_gen != OSD_OII_NOGEN)) {
637                         if (!IS_ERR(inode))
638                                 iput(inode);
639
640                         trusted = true;
641                         goto again;
642                 }
643
644                 if (IS_ERR(inode)) {
645                         if (dev->od_scrub.os_scrub.os_file.sf_flags &
646                             SF_INCONSISTENT)
647                                 /* It still can be the case 2, but we cannot
648                                  * distinguish it from the case 1. So return
649                                  * -EREMCHG to block current operation until
650                                  *  OI scrub rebuilt the OI mappings. */
651                                 rc = -EREMCHG;
652                         else
653                                 rc = -ENOENT;
654
655                         GOTO(put, rc);
656                 }
657
658                 if (inode->i_generation == id->oii_gen)
659                         rc = -ENOENT;
660                 else
661                         rc = -EREMCHG;
662         } else {
663                 if (id->oii_gen == OSD_OII_NOGEN)
664                         osd_id_gen(id, inode->i_ino, inode->i_generation);
665
666                 /* Do not update file c/mtime in ldiskfs.
667                  * NB: we don't have any lock to protect this because we don't
668                  * have reference on osd_object now, but contention with
669                  * another lookup + attr_set can't happen in the tiny window
670                  * between if (...) and set S_NOCMTIME. */
671                 if (!(inode->i_flags & S_NOCMTIME))
672                         inode->i_flags |= S_NOCMTIME;
673         }
674
675         GOTO(put, rc);
676
677 put:
678         if (rc != 0) {
679                 if (!IS_ERR(inode))
680                         iput(inode);
681
682                 inode = ERR_PTR(rc);
683         }
684
685         return inode;
686 }
687
688 /**
689  * \retval +v: new filter_fid, does not contain self-fid
690  * \retval 0:  filter_fid_old, contains self-fid
691  * \retval -v: other failure cases
692  */
693 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
694                  struct dentry *dentry, struct lu_fid *fid)
695 {
696         struct filter_fid_old   *ff     = &info->oti_ff;
697         struct ost_id           *ostid  = &info->oti_ostid;
698         int                      rc;
699
700         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
701         if (rc == sizeof(*ff)) {
702                 rc = 0;
703                 ostid_set_seq(ostid, le64_to_cpu(ff->ff_seq));
704                 rc = ostid_set_id(ostid, le64_to_cpu(ff->ff_objid));
705                 /*
706                  * XXX: use 0 as the index for compatibility, the caller will
707                  *      handle index related issues when necessary.
708                  */
709                 if (!rc)
710                         ostid_to_fid(fid, ostid, 0);
711         } else if (rc == sizeof(struct filter_fid)) {
712                 rc = 1;
713         } else if (rc >= 0) {
714                 rc = -EINVAL;
715         }
716
717         return rc;
718 }
719
720 static int osd_lma_self_repair(struct osd_thread_info *info,
721                                struct osd_device *osd, struct inode *inode,
722                                const struct lu_fid *fid, __u32 compat)
723 {
724         handle_t *jh;
725         int       rc;
726
727         LASSERT(current->journal_info == NULL);
728
729         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
730                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
731         if (IS_ERR(jh)) {
732                 rc = PTR_ERR(jh);
733                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
734                       osd_name(osd), rc);
735                 return rc;
736         }
737
738         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
739         if (rc != 0)
740                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
741                       osd_name(osd), rc);
742         ldiskfs_journal_stop(jh);
743         return rc;
744 }
745
746 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
747 {
748         struct osd_thread_info  *info   = osd_oti_get(env);
749         struct osd_device       *osd    = osd_obj2dev(obj);
750         struct lustre_ost_attrs *loa    = &info->oti_ost_attrs;
751         struct lustre_mdt_attrs *lma    = &loa->loa_lma;
752         struct inode            *inode  = obj->oo_inode;
753         struct dentry           *dentry = &info->oti_obj_dentry;
754         struct lu_fid           *fid    = NULL;
755         const struct lu_fid     *rfid   = lu_object_fid(&obj->oo_dt.do_lu);
756         int                      rc;
757         ENTRY;
758
759         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
760                              (void *)loa, sizeof(*loa));
761         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
762                 fid = &lma->lma_self_fid;
763                 rc = osd_get_idif(info, inode, dentry, fid);
764                 if ((rc > 0) || (rc == -ENODATA && osd->od_index_in_idif)) {
765                         /* For the given OST-object, if it has neither LMA nor
766                          * FID in XATTR_NAME_FID, then the given FID (which is
767                          * contained in the @obj, from client RPC for locating
768                          * the OST-object) is trusted. We use it to generate
769                          * the LMA. */
770                         osd_lma_self_repair(info, osd, inode, rfid,
771                                             LMAC_FID_ON_OST);
772                         RETURN(0);
773                 }
774         }
775
776         if (rc < 0)
777                 RETURN(rc);
778
779         if (rc > 0) {
780                 rc = 0;
781                 lustre_lma_swab(lma);
782                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
783                              (CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT) &&
784                               S_ISREG(inode->i_mode)))) {
785                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
786                               "fid = "DFID", ino = %lu\n", osd_name(osd),
787                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
788                               PFID(rfid), inode->i_ino);
789                         rc = -EOPNOTSUPP;
790                 } else {
791                         fid = &lma->lma_self_fid;
792                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
793                             osd->od_is_ost)
794                                 obj->oo_pfid_in_lma = 1;
795                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
796                             !osd->od_is_ost)
797                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
798                 }
799         }
800
801         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
802                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
803                         struct ost_id   *oi   = &info->oti_ostid;
804                         struct lu_fid   *fid1 = &info->oti_fid3;
805                         __u32            idx  = fid_idif_ost_idx(rfid);
806
807                         /* For old IDIF, the OST index is not part of the IDIF,
808                          * Means that different OSTs may have the same IDIFs.
809                          * Under such case, we need to make some compatible
810                          * check to make sure to trigger OI scrub properly. */
811                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
812                                 /* Given @rfid is new, LMA is old. */
813                                 fid_to_ostid(fid, oi);
814                                 ostid_to_fid(fid1, oi, idx);
815                                 if (lu_fid_eq(fid1, rfid)) {
816                                         if (osd->od_index_in_idif)
817                                                 osd_lma_self_repair(info, osd,
818                                                         inode, rfid,
819                                                         LMAC_FID_ON_OST);
820                                         RETURN(0);
821                                 }
822                         }
823                 }
824
825                 rc = -EREMCHG;
826         }
827
828         RETURN(rc);
829 }
830
831 struct osd_check_lmv_buf {
832 #ifdef HAVE_DIR_CONTEXT
833         /* please keep it as first member */
834         struct dir_context       ctx;
835 #endif
836         struct osd_thread_info  *oclb_info;
837         struct osd_device       *oclb_dev;
838         struct osd_idmap_cache  *oclb_oic;
839         int                      oclb_items;
840         bool                     oclb_found;
841 };
842
843 /**
844  * It is called internally by ->readdir() to filter out the
845  * local slave object's FID of the striped directory.
846  *
847  * \retval      1 found the local slave's FID
848  * \retval      0 continue to check next item
849  * \retval      -ve for failure
850  */
851 #ifdef HAVE_FILLDIR_USE_CTX
852 static int osd_stripe_dir_filldir(struct dir_context *buf,
853 #else
854 static int osd_stripe_dir_filldir(void *buf,
855 #endif
856                                   const char *name, int namelen,
857                                   loff_t offset, __u64 ino, unsigned d_type)
858 {
859         struct osd_check_lmv_buf *oclb = (struct osd_check_lmv_buf *)buf;
860         struct osd_thread_info *oti = oclb->oclb_info;
861         struct lu_fid *fid = &oti->oti_fid3;
862         struct osd_inode_id *id = &oti->oti_id3;
863         struct osd_device *dev = oclb->oclb_dev;
864         struct osd_idmap_cache *oic = oclb->oclb_oic;
865         struct inode *inode;
866
867         oclb->oclb_items++;
868
869         if (name[0] == '.')
870                 return 0;
871
872         fid_zero(fid);
873         sscanf(name + 1, SFID, RFID(fid));
874         if (!fid_is_sane(fid))
875                 return 0;
876
877         if (osd_remote_fid(oti->oti_env, dev, fid))
878                 return 0;
879
880         osd_id_gen(id, ino, OSD_OII_NOGEN);
881         inode = osd_iget(oti, dev, id);
882         if (IS_ERR(inode))
883                 return PTR_ERR(inode);
884
885         iput(inode);
886         osd_add_oi_cache(oti, dev, id, fid);
887         oic->oic_fid = *fid;
888         oic->oic_lid = *id;
889         oic->oic_dev = dev;
890         osd_oii_insert(dev, oic, true);
891         oclb->oclb_found = true;
892
893         return 1;
894 }
895
896 /* When lookup item under striped directory, we need to locate the master
897  * MDT-object of the striped directory firstly, then the client will send
898  * lookup (getattr_by_name) RPC to the MDT with some slave MDT-object's FID
899  * and the item's name. If the system is restored from MDT file level backup,
900  * then before the OI scrub completely built the OI files, the OI mappings of
901  * the master MDT-object and slave MDT-object may be invalid. Usually, it is
902  * not a problem for the master MDT-object. Because when locate the master
903  * MDT-object, we will do name based lookup (for the striped directory itself)
904  * firstly, during such process we can setup the correct OI mapping for the
905  * master MDT-object. But it will be trouble for the slave MDT-object. Because
906  * the client will not trigger name based lookup on the MDT to locate the slave
907  * MDT-object before locating item under the striped directory, then when
908  * osd_fid_lookup(), it will find that the OI mapping for the slave MDT-object
909  * is invalid and does not know what the right OI mapping is, then the MDT has
910  * to return -EINPROGRESS to the client to notify that the OI scrub is rebuiding
911  * the OI file, related OI mapping is unknown yet, please try again later. And
912  * then client will re-try the RPC again and again until related OI mapping has
913  * been updated. That is quite inefficient.
914  *
915  * To resolve above trouble, we will handle it as the following two cases:
916  *
917  * 1) The slave MDT-object and the master MDT-object are on different MDTs.
918  *    It is relative easy. Be as one of remote MDT-objects, the slave MDT-object
919  *    is linked under /REMOTE_PARENT_DIR with the name of its FID string.
920  *    We can locate the slave MDT-object via lookup the /REMOTE_PARENT_DIR
921  *    directly. Please check osd_fid_lookup().
922  *
923  * 2) The slave MDT-object and the master MDT-object reside on the same MDT.
924  *    Under such case, during lookup the master MDT-object, we will lookup the
925  *    slave MDT-object via readdir against the master MDT-object, because the
926  *    slave MDT-objects information are stored as sub-directories with the name
927  *    "${FID}:${index}". Then when find the local slave MDT-object, its OI
928  *    mapping will be recorded. Then subsequent osd_fid_lookup() will know
929  *    the correct OI mapping for the slave MDT-object. */
930 static int osd_check_lmv(struct osd_thread_info *oti, struct osd_device *dev,
931                          struct inode *inode, struct osd_idmap_cache *oic)
932 {
933         struct lu_buf *buf = &oti->oti_big_buf;
934         struct dentry *dentry = &oti->oti_obj_dentry;
935         struct file *filp = &oti->oti_file;
936         const struct file_operations *fops;
937         struct lmv_mds_md_v1 *lmv1;
938         struct osd_check_lmv_buf oclb = {
939 #ifdef HAVE_DIR_CONTEXT
940                 .ctx.actor = osd_stripe_dir_filldir,
941 #endif
942                 .oclb_info = oti,
943                 .oclb_dev = dev,
944                 .oclb_oic = oic,
945                 .oclb_found = false,
946         };
947         int rc = 0;
948         ENTRY;
949
950 again:
951         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMV, buf->lb_buf,
952                              buf->lb_len);
953         if (rc == -ERANGE) {
954                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMV, NULL, 0);
955                 if (rc > 0) {
956                         lu_buf_realloc(buf, rc);
957                         if (buf->lb_buf == NULL)
958                                 GOTO(out, rc = -ENOMEM);
959
960                         goto again;
961                 }
962         }
963
964         if (unlikely(rc == 0 || rc == -ENODATA))
965                 GOTO(out, rc = 0);
966
967         if (rc < 0)
968                 GOTO(out, rc);
969
970         if (unlikely(buf->lb_buf == NULL)) {
971                 lu_buf_realloc(buf, rc);
972                 if (buf->lb_buf == NULL)
973                         GOTO(out, rc = -ENOMEM);
974
975                 goto again;
976         }
977
978         lmv1 = buf->lb_buf;
979         if (le32_to_cpu(lmv1->lmv_magic) != LMV_MAGIC_V1)
980                 GOTO(out, rc = 0);
981
982         fops = inode->i_fop;
983         dentry->d_inode = inode;
984         dentry->d_sb = inode->i_sb;
985         filp->f_pos = 0;
986         filp->f_path.dentry = dentry;
987         filp->f_mode = FMODE_64BITHASH;
988         filp->f_mapping = inode->i_mapping;
989         filp->f_op = fops;
990         filp->private_data = NULL;
991         set_file_inode(filp, inode);
992
993         do {
994                 oclb.oclb_items = 0;
995 #ifdef HAVE_DIR_CONTEXT
996                 oclb.ctx.pos = filp->f_pos;
997                 rc = fops->iterate(filp, &oclb.ctx);
998                 filp->f_pos = oclb.ctx.pos;
999 #else
1000                 rc = fops->readdir(filp, &oclb, osd_stripe_dir_filldir);
1001 #endif
1002         } while (rc >= 0 && oclb.oclb_items > 0 && !oclb.oclb_found &&
1003                  filp->f_pos != LDISKFS_HTREE_EOF_64BIT);
1004         fops->release(inode, filp);
1005
1006 out:
1007         if (rc < 0)
1008                 CDEBUG(D_LFSCK, "%s: fail to check LMV EA, inode = %lu/%u,"
1009                        DFID": rc = %d\n", osd_ino2name(inode),
1010                        inode->i_ino, inode->i_generation,
1011                        PFID(&oic->oic_fid), rc);
1012         else
1013                 rc = 0;
1014
1015         RETURN(rc);
1016 }
1017
1018 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
1019                           const struct lu_fid *fid,
1020                           const struct lu_object_conf *conf)
1021 {
1022         struct osd_thread_info *info;
1023         struct lu_device *ldev = obj->oo_dt.do_lu.lo_dev;
1024         struct osd_device *dev;
1025         struct osd_idmap_cache *oic;
1026         struct osd_inode_id *id;
1027         struct inode *inode = NULL;
1028         struct lustre_scrub *scrub;
1029         struct scrub_file *sf;
1030         __u32 flags = SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT | SS_AUTO_FULL;
1031         __u32 saved_ino;
1032         __u32 saved_gen;
1033         int result = 0;
1034         int rc1 = 0;
1035         bool remote = false;
1036         bool trusted = true;
1037         bool updated = false;
1038         bool checked = false;
1039         ENTRY;
1040
1041         LINVRNT(osd_invariant(obj));
1042         LASSERT(obj->oo_inode == NULL);
1043         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID"\n", PFID(fid));
1044
1045         dev = osd_dev(ldev);
1046         scrub = &dev->od_scrub.os_scrub;
1047         sf = &scrub->os_file;
1048         info = osd_oti_get(env);
1049         LASSERT(info);
1050         oic = &info->oti_cache;
1051
1052         if (OBD_FAIL_CHECK(OBD_FAIL_SRV_ENOENT))
1053                 RETURN(-ENOENT);
1054
1055         /* For the object is created as locking anchor, or for the object to
1056          * be created on disk. No need to osd_oi_lookup() at here because FID
1057          * shouldn't never be re-used, if it's really a duplicate FID from
1058          * unexpected reason, we should be able to detect it later by calling
1059          * do_create->osd_oi_insert(). */
1060         if (conf && conf->loc_flags & LOC_F_NEW)
1061                 GOTO(out, result = 0);
1062
1063         /* Search order: 1. per-thread cache. */
1064         if (lu_fid_eq(fid, &oic->oic_fid) && likely(oic->oic_dev == dev)) {
1065                 id = &oic->oic_lid;
1066                 goto iget;
1067         }
1068
1069         id = &info->oti_id;
1070         if (!list_empty(&scrub->os_inconsistent_items)) {
1071                 /* Search order: 2. OI scrub pending list. */
1072                 result = osd_oii_lookup(dev, fid, id);
1073                 if (!result)
1074                         goto iget;
1075         }
1076
1077         /* The OI mapping in the OI file can be updated by the OI scrub
1078          * when we locate the inode via FID. So it may be not trustable. */
1079         trusted = false;
1080
1081         /* Search order: 3. OI files. */
1082         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1083         if (result == -ENOENT) {
1084                 if (!(fid_is_norm(fid) || fid_is_igif(fid)) ||
1085                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
1086                     !ldiskfs_test_bit(osd_oi_fid2idx(dev,fid),
1087                                       sf->sf_oi_bitmap))
1088                         GOTO(out, result = 0);
1089
1090                 goto trigger;
1091         }
1092
1093         if (result)
1094                 GOTO(out, result);
1095
1096 iget:
1097         obj->oo_inode = NULL;
1098         /* for later passes through checks, not true on first pass */
1099         if (!IS_ERR_OR_NULL(inode))
1100                 iput(inode);
1101
1102         inode = osd_iget_check(info, dev, fid, id, trusted);
1103         if (!IS_ERR(inode)) {
1104                 obj->oo_inode = inode;
1105                 result = 0;
1106                 if (remote)
1107                         goto trigger;
1108
1109                 goto check_lma;
1110         }
1111
1112         result = PTR_ERR(inode);
1113         if (result == -ENOENT || result == -ESTALE)
1114                 GOTO(out, result = 0);
1115
1116         if (result != -EREMCHG)
1117                 GOTO(out, result);
1118
1119 trigger:
1120         /* We still have chance to get the valid inode: for the
1121          * object which is referenced by remote name entry, the
1122          * object on the local MDT will be linked under the dir
1123          * of "/REMOTE_PARENT_DIR" with its FID string as name.
1124          *
1125          * We do not know whether the object for the given FID
1126          * is referenced by some remote name entry or not, and
1127          * especially for DNE II, a multiple-linked object may
1128          * have many name entries reside on many MDTs.
1129          *
1130          * To simplify the operation, OSD will not distinguish
1131          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
1132          * only happened for the RPC from other MDT during the
1133          * OI scrub, or for the client side RPC with FID only,
1134          * such as FID to path, or from old connected client. */
1135         if (!remote && !fid_is_on_ost(info, dev, fid, OI_CHECK_FLD)) {
1136                 rc1 = osd_lookup_in_remote_parent(info, dev, fid, id);
1137                 if (!rc1) {
1138                         remote = true;
1139                         trusted = true;
1140                         flags |= SS_AUTO_PARTIAL;
1141                         flags &= ~SS_AUTO_FULL;
1142                         goto iget;
1143                 }
1144         }
1145
1146         if (thread_is_running(&scrub->os_thread)) {
1147                 if (scrub->os_partial_scan && !scrub->os_in_join)
1148                         goto join;
1149
1150                 if (IS_ERR_OR_NULL(inode) || result)
1151                         GOTO(out, result = -EINPROGRESS);
1152
1153                 LASSERT(remote);
1154                 LASSERT(obj->oo_inode == inode);
1155
1156                 osd_add_oi_cache(info, dev, id, fid);
1157                 osd_oii_insert(dev, oic, true);
1158                 goto found;
1159         }
1160
1161         if (dev->od_auto_scrub_interval == AS_NEVER) {
1162                 if (!remote)
1163                         GOTO(out, result = -EREMCHG);
1164
1165                 LASSERT(!result);
1166                 LASSERT(obj->oo_inode == inode);
1167
1168                 osd_add_oi_cache(info, dev, id, fid);
1169                 goto found;
1170         }
1171
1172 join:
1173         rc1 = osd_scrub_start(env, dev, flags);
1174         LCONSOLE_WARN("%s: trigger OI scrub by RPC for the " DFID" with flags "
1175                       "0x%x, rc = %d\n", osd_name(dev), PFID(fid), flags, rc1);
1176         if (rc1 && rc1 != -EALREADY)
1177                 GOTO(out, result = -EREMCHG);
1178
1179         if (IS_ERR_OR_NULL(inode) || result)
1180                 GOTO(out, result = -EINPROGRESS);
1181
1182         LASSERT(remote);
1183         LASSERT(obj->oo_inode == inode);
1184
1185         osd_add_oi_cache(info, dev, id, fid);
1186         osd_oii_insert(dev, oic, true);
1187         goto found;
1188
1189 check_lma:
1190         checked = true;
1191         if (unlikely(obj->oo_header))
1192                 goto found;
1193
1194         result = osd_check_lma(env, obj);
1195         if (!result)
1196                 goto found;
1197
1198         LASSERTF(id->oii_ino == inode->i_ino &&
1199                  id->oii_gen == inode->i_generation,
1200                  "locate wrong inode for FID: "DFID", %u/%u => %ld/%u\n",
1201                  PFID(fid), id->oii_ino, id->oii_gen,
1202                  inode->i_ino, inode->i_generation);
1203
1204         saved_ino = inode->i_ino;
1205         saved_gen = inode->i_generation;
1206
1207         if (unlikely(result == -ENODATA)) {
1208                 /* If the OI scrub updated the OI mapping by race, it
1209                  * must be valid. Trust the inode that has no LMA EA. */
1210                 if (updated)
1211                         goto found;
1212
1213                 result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1214                 if (!result) {
1215                         /* The OI mapping is still there, the inode is still
1216                          * valid. It is just becaues the inode has no LMA EA. */
1217                         if (saved_ino == id->oii_ino &&
1218                             saved_gen == id->oii_gen)
1219                                 goto found;
1220
1221                         /* It is the OI scrub updated the OI mapping by race.
1222                          * The new OI mapping must be valid. */
1223                         trusted = true;
1224                         updated = true;
1225                         goto iget;
1226                 }
1227
1228                 /* "result == -ENOENT" means that the OI mappinghas been
1229                  * removed by race, so the inode belongs to other object.
1230                  *
1231                  * Others error can be returned  directly. */
1232                 if (result == -ENOENT) {
1233                         LASSERT(trusted);
1234
1235                         obj->oo_inode = NULL;
1236                         result = 0;
1237                 }
1238         }
1239
1240         if (result != -EREMCHG)
1241                 GOTO(out, result);
1242
1243         LASSERT(!updated);
1244
1245         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1246         /* "result == -ENOENT" means the cached OI mapping has been removed
1247          * from the OI file by race, above inode belongs to other object. */
1248         if (result == -ENOENT) {
1249                 LASSERT(trusted);
1250
1251                 obj->oo_inode = NULL;
1252                 GOTO(out, result = 0);
1253         }
1254
1255         if (result)
1256                 GOTO(out, result);
1257
1258         if (saved_ino == id->oii_ino && saved_gen == id->oii_gen) {
1259                 result = -EREMCHG;
1260                 goto trigger;
1261         }
1262
1263         /* It is the OI scrub updated the OI mapping by race.
1264          * The new OI mapping must be valid. */
1265         trusted = true;
1266         updated = true;
1267         goto iget;
1268
1269 found:
1270         if (!checked) {
1271                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
1272                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
1273
1274                 result = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
1275                 if (!result) {
1276                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
1277                             dev->od_is_ost)
1278                                 obj->oo_pfid_in_lma = 1;
1279                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
1280                             !dev->od_is_ost)
1281                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
1282                 } else if (result != -ENODATA) {
1283                         GOTO(out, result);
1284                 }
1285         }
1286
1287         obj->oo_compat_dot_created = 1;
1288         obj->oo_compat_dotdot_created = 1;
1289
1290         if (S_ISDIR(inode->i_mode) &&
1291             (flags & SS_AUTO_PARTIAL || sf->sf_status == SS_SCANNING))
1292                 osd_check_lmv(info, dev, inode, oic);
1293
1294         result = osd_attach_jinode(inode);
1295         if (result)
1296                 GOTO(out, result);
1297
1298         if (!ldiskfs_pdo)
1299                 GOTO(out, result = 0);
1300
1301         LASSERT(!obj->oo_hl_head);
1302         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1303
1304         GOTO(out, result = (!obj->oo_hl_head ? -ENOMEM : 0));
1305
1306 out:
1307         if (result || !obj->oo_inode) {
1308                 if (!IS_ERR_OR_NULL(inode))
1309                         iput(inode);
1310
1311                 obj->oo_inode = NULL;
1312                 if (trusted)
1313                         fid_zero(&oic->oic_fid);
1314         }
1315
1316         LINVRNT(osd_invariant(obj));
1317         return result;
1318 }
1319
1320 /*
1321  * Concurrency: shouldn't matter.
1322  */
1323 static void osd_object_init0(struct osd_object *obj)
1324 {
1325         LASSERT(obj->oo_inode != NULL);
1326         obj->oo_dt.do_body_ops = &osd_body_ops;
1327         obj->oo_dt.do_lu.lo_header->loh_attr |=
1328                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
1329 }
1330
1331 /*
1332  * Concurrency: no concurrent access is possible that early in object
1333  * life-cycle.
1334  */
1335 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
1336                            const struct lu_object_conf *conf)
1337 {
1338         struct osd_object *obj = osd_obj(l);
1339         int result;
1340
1341         LINVRNT(osd_invariant(obj));
1342
1343         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
1344                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
1345                 l->lo_header->loh_attr |= LOHA_EXISTS;
1346                 return 0;
1347         }
1348
1349         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
1350         obj->oo_dt.do_body_ops = &osd_body_ops_new;
1351         if (result == 0 && obj->oo_inode != NULL) {
1352                 struct osd_thread_info *oti = osd_oti_get(env);
1353                 struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
1354
1355                 osd_object_init0(obj);
1356                 if (unlikely(obj->oo_header))
1357                         return 0;
1358
1359                 result = osd_get_lma(oti, obj->oo_inode,
1360                                      &oti->oti_obj_dentry, loa);
1361                 if (!result) {
1362                         /* Convert LMAI flags to lustre LMA flags
1363                          * and cache it to oo_lma_flags */
1364                         obj->oo_lma_flags =
1365                                 lma_to_lustre_flags(loa->loa_lma.lma_incompat);
1366                 } else if (result == -ENODATA) {
1367                         result = 0;
1368                 }
1369         }
1370
1371         LINVRNT(osd_invariant(obj));
1372         return result;
1373 }
1374
1375 /* The first part of oxe_buf is xattr name, and is '\0' terminated.
1376  * The left part is for value, binary mode. */
1377 struct osd_xattr_entry {
1378         struct list_head        oxe_list;
1379         size_t                  oxe_len;
1380         size_t                  oxe_namelen;
1381         bool                    oxe_exist;
1382         struct rcu_head         oxe_rcu;
1383         char                    oxe_buf[0];
1384 };
1385
1386 static int osd_oxc_get(struct osd_object *obj, const char *name,
1387                        struct lu_buf *buf)
1388 {
1389         struct osd_xattr_entry *tmp;
1390         struct osd_xattr_entry *oxe = NULL;
1391         size_t namelen = strlen(name);
1392         int rc;
1393         ENTRY;
1394
1395         rcu_read_lock();
1396         list_for_each_entry_rcu(tmp, &obj->oo_xattr_list, oxe_list) {
1397                 if (namelen == tmp->oxe_namelen &&
1398                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1399                         oxe = tmp;
1400                         break;
1401                 }
1402         }
1403
1404         if (oxe == NULL)
1405                 GOTO(out, rc = -ENOENT);
1406
1407         if (!oxe->oxe_exist)
1408                 GOTO(out, rc = -ENODATA);
1409
1410         /* vallen */
1411         rc = oxe->oxe_len - sizeof(*oxe) - oxe->oxe_namelen - 1;
1412         LASSERT(rc > 0);
1413
1414         if (buf->lb_buf == NULL)
1415                 GOTO(out, rc);
1416
1417         if (buf->lb_len < rc)
1418                 GOTO(out, rc = -ERANGE);
1419
1420         memcpy(buf->lb_buf, &oxe->oxe_buf[namelen + 1], rc);
1421         EXIT;
1422 out:
1423         rcu_read_unlock();
1424
1425         return rc;
1426 }
1427
1428 static void osd_oxc_free(struct rcu_head *head)
1429 {
1430         struct osd_xattr_entry *oxe;
1431
1432         oxe = container_of(head, struct osd_xattr_entry, oxe_rcu);
1433         OBD_FREE(oxe, oxe->oxe_len);
1434 }
1435
1436 static void osd_oxc_add(struct osd_object *obj, const char *name,
1437                         const char *buf, int buflen)
1438 {
1439         struct osd_xattr_entry *oxe;
1440         struct osd_xattr_entry *old = NULL;
1441         struct osd_xattr_entry *tmp;
1442         size_t namelen = strlen(name);
1443         size_t len = sizeof(*oxe) + namelen + 1 + buflen;
1444
1445         OBD_ALLOC(oxe, len);
1446         if (oxe == NULL)
1447                 return;
1448
1449         INIT_LIST_HEAD(&oxe->oxe_list);
1450         oxe->oxe_len = len;
1451         oxe->oxe_namelen = namelen;
1452         memcpy(oxe->oxe_buf, name, namelen);
1453         if (buflen > 0) {
1454                 LASSERT(buf != NULL);
1455                 memcpy(oxe->oxe_buf + namelen + 1, buf, buflen);
1456                 oxe->oxe_exist = true;
1457         } else {
1458                 oxe->oxe_exist = false;
1459         }
1460
1461         /* this should be rarely called, just remove old and add new */
1462         spin_lock(&obj->oo_guard);
1463         list_for_each_entry(tmp, &obj->oo_xattr_list, oxe_list) {
1464                 if (namelen == tmp->oxe_namelen &&
1465                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1466                         old = tmp;
1467                         break;
1468                 }
1469         }
1470         if (old != NULL) {
1471                 list_replace_rcu(&old->oxe_list, &oxe->oxe_list);
1472                 call_rcu(&old->oxe_rcu, osd_oxc_free);
1473         } else {
1474                 list_add_tail_rcu(&oxe->oxe_list, &obj->oo_xattr_list);
1475         }
1476         spin_unlock(&obj->oo_guard);
1477 }
1478
1479 static void osd_oxc_del(struct osd_object *obj, const char *name)
1480 {
1481         struct osd_xattr_entry *oxe;
1482         size_t namelen = strlen(name);
1483
1484         spin_lock(&obj->oo_guard);
1485         list_for_each_entry(oxe, &obj->oo_xattr_list, oxe_list) {
1486                 if (namelen == oxe->oxe_namelen &&
1487                     strncmp(name, oxe->oxe_buf, namelen) == 0) {
1488                         list_del_rcu(&oxe->oxe_list);
1489                         call_rcu(&oxe->oxe_rcu, osd_oxc_free);
1490                         break;
1491                 }
1492         }
1493         spin_unlock(&obj->oo_guard);
1494 }
1495
1496 static void osd_oxc_fini(struct osd_object *obj)
1497 {
1498         struct osd_xattr_entry *oxe, *next;
1499
1500         list_for_each_entry_safe(oxe, next, &obj->oo_xattr_list, oxe_list) {
1501                 list_del(&oxe->oxe_list);
1502                 OBD_FREE(oxe, oxe->oxe_len);
1503         }
1504 }
1505
1506 /*
1507  * Concurrency: no concurrent access is possible that late in object
1508  * life-cycle.
1509  */
1510 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
1511 {
1512         struct osd_object *obj = osd_obj(l);
1513         struct lu_object_header *h = obj->oo_header;
1514
1515         LINVRNT(osd_invariant(obj));
1516
1517         osd_oxc_fini(obj);
1518         dt_object_fini(&obj->oo_dt);
1519         if (obj->oo_hl_head != NULL)
1520                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1521         OBD_FREE_PTR(obj);
1522         if (unlikely(h)) {
1523                 lu_object_header_fini(h);
1524                 OBD_FREE_PTR(h);
1525         }
1526 }
1527
1528 /*
1529  * Concurrency: no concurrent access is possible that late in object
1530  * life-cycle.
1531  */
1532 static void osd_index_fini(struct osd_object *o)
1533 {
1534         struct iam_container *bag;
1535
1536         if (o->oo_dir != NULL) {
1537                 bag = &o->oo_dir->od_container;
1538                 if (o->oo_inode != NULL) {
1539                         if (bag->ic_object == o->oo_inode)
1540                                 iam_container_fini(bag);
1541                 }
1542                 OBD_FREE_PTR(o->oo_dir);
1543                 o->oo_dir = NULL;
1544         }
1545 }
1546
1547 /*
1548  * Concurrency: no concurrent access is possible that late in object
1549  * life-cycle (for all existing callers, that is. New callers have to provide
1550  * their own locking.)
1551  */
1552 static int osd_inode_unlinked(const struct inode *inode)
1553 {
1554         return inode->i_nlink == 0;
1555 }
1556
1557 enum {
1558         OSD_TXN_OI_DELETE_CREDITS    = 20,
1559         OSD_TXN_INODE_DELETE_CREDITS = 20
1560 };
1561
1562 /*
1563  * Journal
1564  */
1565
1566 #if OSD_THANDLE_STATS
1567 /**
1568  * Set time when the handle is allocated
1569  */
1570 static void osd_th_alloced(struct osd_thandle *oth)
1571 {
1572         oth->oth_alloced = ktime_get();
1573 }
1574
1575 /**
1576  * Set time when the handle started
1577  */
1578 static void osd_th_started(struct osd_thandle *oth)
1579 {
1580         oth->oth_started = ktime_get();
1581 }
1582
1583 /**
1584  * Check whether the we deal with this handle for too long.
1585  */
1586 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
1587                                 ktime_t alloced, ktime_t started,
1588                                 ktime_t closed)
1589 {
1590         ktime_t now = ktime_get();
1591
1592         LASSERT(dev != NULL);
1593
1594         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
1595                             ktime_us_delta(started, alloced));
1596         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
1597                             ktime_us_delta(closed, started));
1598         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
1599                             ktime_us_delta(now, closed));
1600
1601         if (ktime_before(ktime_add_ns(alloced, 30 * NSEC_PER_SEC), now)) {
1602                 CWARN("transaction handle %p was open for too long: now %lld, alloced %lld, started %lld, closed %lld\n",
1603                       oth, now, alloced, started, closed);
1604                 libcfs_debug_dumpstack(NULL);
1605         }
1606 }
1607
1608 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
1609 {                                                                       \
1610         ktime_t __closed = ktime_get();                                 \
1611         ktime_t __alloced = oth->oth_alloced;                           \
1612         ktime_t __started = oth->oth_started;                           \
1613                                                                         \
1614         expr;                                                           \
1615         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
1616 }
1617
1618 #else /* OSD_THANDLE_STATS */
1619
1620 #define osd_th_alloced(h)                  do {} while(0)
1621 #define osd_th_started(h)                  do {} while(0)
1622 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
1623
1624 #endif /* OSD_THANDLE_STATS */
1625
1626 /*
1627  * Concurrency: doesn't access mutable data.
1628  */
1629 static int osd_param_is_not_sane(const struct osd_device *dev,
1630                                  const struct thandle *th)
1631 {
1632         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
1633
1634         return oh->ot_credits > osd_transaction_size(dev);
1635 }
1636
1637 /*
1638  * Concurrency: shouldn't matter.
1639  */
1640 static void osd_trans_commit_cb(struct super_block *sb,
1641                                 struct ldiskfs_journal_cb_entry *jcb, int error)
1642 {
1643         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
1644         struct thandle     *th  = &oh->ot_super;
1645         struct lu_device   *lud = &th->th_dev->dd_lu_dev;
1646         struct dt_txn_commit_cb *dcb, *tmp;
1647
1648         LASSERT(oh->ot_handle == NULL);
1649
1650         if (error)
1651                 CERROR("transaction @0x%p commit error: %d\n", th, error);
1652
1653         dt_txn_hook_commit(th);
1654
1655         /* call per-transaction callbacks if any */
1656         list_for_each_entry_safe(dcb, tmp, &oh->ot_commit_dcb_list,
1657                                  dcb_linkage) {
1658                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1659                          "commit callback entry: magic=%x name='%s'\n",
1660                          dcb->dcb_magic, dcb->dcb_name);
1661                 list_del_init(&dcb->dcb_linkage);
1662                 dcb->dcb_func(NULL, th, dcb, error);
1663         }
1664
1665         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
1666         lu_device_put(lud);
1667         th->th_dev = NULL;
1668
1669         OBD_FREE_PTR(oh);
1670 }
1671
1672 #ifndef HAVE_SB_START_WRITE
1673 # define sb_start_write(sb) do {} while (0)
1674 # define sb_end_write(sb) do {} while (0)
1675 #endif
1676
1677 static struct thandle *osd_trans_create(const struct lu_env *env,
1678                                         struct dt_device *d)
1679 {
1680         struct osd_thread_info  *oti = osd_oti_get(env);
1681         struct osd_iobuf        *iobuf = &oti->oti_iobuf;
1682         struct osd_thandle      *oh;
1683         struct thandle          *th;
1684         ENTRY;
1685
1686         if (d->dd_rdonly) {
1687                 CERROR("%s: someone try to start transaction under "
1688                        "readonly mode, should be disabled.\n",
1689                        osd_name(osd_dt_dev(d)));
1690                 dump_stack();
1691                 RETURN(ERR_PTR(-EROFS));
1692         }
1693
1694         /* on pending IO in this thread should left from prev. request */
1695         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
1696
1697         sb_start_write(osd_sb(osd_dt_dev(d)));
1698
1699         OBD_ALLOC_GFP(oh, sizeof *oh, GFP_NOFS);
1700         if (!oh) {
1701                 sb_end_write(osd_sb(osd_dt_dev(d)));
1702                 RETURN(ERR_PTR(-ENOMEM));
1703         }
1704
1705         oh->ot_quota_trans = &oti->oti_quota_trans;
1706         memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
1707         th = &oh->ot_super;
1708         th->th_dev = d;
1709         th->th_result = 0;
1710         oh->ot_credits = 0;
1711         INIT_LIST_HEAD(&oh->ot_commit_dcb_list);
1712         INIT_LIST_HEAD(&oh->ot_stop_dcb_list);
1713         osd_th_alloced(oh);
1714
1715         memset(oti->oti_declare_ops, 0,
1716                sizeof(oti->oti_declare_ops));
1717         memset(oti->oti_declare_ops_cred, 0,
1718                sizeof(oti->oti_declare_ops_cred));
1719         memset(oti->oti_declare_ops_used, 0,
1720                sizeof(oti->oti_declare_ops_used));
1721
1722         oti->oti_ins_cache_depth++;
1723
1724         RETURN(th);
1725 }
1726
1727 void osd_trans_dump_creds(const struct lu_env *env, struct thandle *th)
1728 {
1729         struct osd_thread_info  *oti = osd_oti_get(env);
1730         struct osd_thandle      *oh;
1731
1732         oh = container_of0(th, struct osd_thandle, ot_super);
1733         LASSERT(oh != NULL);
1734
1735         CWARN("  create: %u/%u/%u, destroy: %u/%u/%u\n",
1736               oti->oti_declare_ops[OSD_OT_CREATE],
1737               oti->oti_declare_ops_cred[OSD_OT_CREATE],
1738               oti->oti_declare_ops_used[OSD_OT_CREATE],
1739               oti->oti_declare_ops[OSD_OT_DESTROY],
1740               oti->oti_declare_ops_cred[OSD_OT_DESTROY],
1741               oti->oti_declare_ops_used[OSD_OT_DESTROY]);
1742         CWARN("  attr_set: %u/%u/%u, xattr_set: %u/%u/%u\n",
1743               oti->oti_declare_ops[OSD_OT_ATTR_SET],
1744               oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1745               oti->oti_declare_ops_used[OSD_OT_ATTR_SET],
1746               oti->oti_declare_ops[OSD_OT_XATTR_SET],
1747               oti->oti_declare_ops_cred[OSD_OT_XATTR_SET],
1748               oti->oti_declare_ops_used[OSD_OT_XATTR_SET]);
1749         CWARN("  write: %u/%u/%u, punch: %u/%u/%u, quota %u/%u/%u\n",
1750               oti->oti_declare_ops[OSD_OT_WRITE],
1751               oti->oti_declare_ops_cred[OSD_OT_WRITE],
1752               oti->oti_declare_ops_used[OSD_OT_WRITE],
1753               oti->oti_declare_ops[OSD_OT_PUNCH],
1754               oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1755               oti->oti_declare_ops_used[OSD_OT_PUNCH],
1756               oti->oti_declare_ops[OSD_OT_QUOTA],
1757               oti->oti_declare_ops_cred[OSD_OT_QUOTA],
1758               oti->oti_declare_ops_used[OSD_OT_QUOTA]);
1759         CWARN("  insert: %u/%u/%u, delete: %u/%u/%u\n",
1760               oti->oti_declare_ops[OSD_OT_INSERT],
1761               oti->oti_declare_ops_cred[OSD_OT_INSERT],
1762               oti->oti_declare_ops_used[OSD_OT_INSERT],
1763               oti->oti_declare_ops[OSD_OT_DELETE],
1764               oti->oti_declare_ops_cred[OSD_OT_DELETE],
1765               oti->oti_declare_ops_used[OSD_OT_DELETE]);
1766         CWARN("  ref_add: %u/%u/%u, ref_del: %u/%u/%u\n",
1767               oti->oti_declare_ops[OSD_OT_REF_ADD],
1768               oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1769               oti->oti_declare_ops_used[OSD_OT_REF_ADD],
1770               oti->oti_declare_ops[OSD_OT_REF_DEL],
1771               oti->oti_declare_ops_cred[OSD_OT_REF_DEL],
1772               oti->oti_declare_ops_used[OSD_OT_REF_DEL]);
1773 }
1774
1775 /*
1776  * Concurrency: shouldn't matter.
1777  */
1778 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
1779                            struct thandle *th)
1780 {
1781         struct osd_thread_info *oti = osd_oti_get(env);
1782         struct osd_device  *dev = osd_dt_dev(d);
1783         handle_t           *jh;
1784         struct osd_thandle *oh;
1785         int rc;
1786
1787         ENTRY;
1788
1789         LASSERT(current->journal_info == NULL);
1790
1791         oh = container_of0(th, struct osd_thandle, ot_super);
1792         LASSERT(oh != NULL);
1793         LASSERT(oh->ot_handle == NULL);
1794
1795         rc = dt_txn_hook_start(env, d, th);
1796         if (rc != 0)
1797                 GOTO(out, rc);
1798
1799         if (unlikely(osd_param_is_not_sane(dev, th))) {
1800                 static unsigned long last_printed;
1801                 static int last_credits;
1802
1803                 /* don't make noise on a tiny testing systems
1804                  * actual credits misuse will be caught anyway */
1805                 if (last_credits != oh->ot_credits &&
1806                     time_after(jiffies, last_printed +
1807                                msecs_to_jiffies(60 * MSEC_PER_SEC)) &&
1808                     osd_transaction_size(dev) > 512) {
1809                         CWARN("%s: credits %u > trans_max %u\n", osd_name(dev),
1810                               oh->ot_credits, osd_transaction_size(dev));
1811                         osd_trans_dump_creds(env, th);
1812                         libcfs_debug_dumpstack(NULL);
1813                         last_credits = oh->ot_credits;
1814                         last_printed = jiffies;
1815                 }
1816                 /* XXX Limit the credits to 'max_transaction_buffers', and
1817                  *     let the underlying filesystem to catch the error if
1818                  *     we really need so many credits.
1819                  *
1820                  *     This should be removed when we can calculate the
1821                  *     credits precisely. */
1822                 oh->ot_credits = osd_transaction_size(dev);
1823         } else if (ldiskfs_track_declares_assert != 0) {
1824                 /* reserve few credits to prevent an assertion in JBD
1825                  * our debugging mechanism will be able to detected
1826                  * overuse. this can help to debug single-update
1827                  * transactions */
1828                 oh->ot_credits += 10;
1829                 if (unlikely(osd_param_is_not_sane(dev, th)))
1830                         oh->ot_credits = osd_transaction_size(dev);
1831         }
1832
1833         /*
1834          * XXX temporary stuff. Some abstraction layer should
1835          * be used.
1836          */
1837         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
1838         osd_th_started(oh);
1839         if (!IS_ERR(jh)) {
1840                 oh->ot_handle = jh;
1841                 LASSERT(oti->oti_txns == 0);
1842
1843                 lu_device_get(&d->dd_lu_dev);
1844                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
1845                               "osd-tx", th);
1846                 oti->oti_txns++;
1847                 rc = 0;
1848         } else {
1849                 rc = PTR_ERR(jh);
1850         }
1851 out:
1852         RETURN(rc);
1853 }
1854
1855 static int osd_seq_exists(const struct lu_env *env,
1856                           struct osd_device *osd, u64 seq)
1857 {
1858         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
1859         struct seq_server_site  *ss = osd_seq_site(osd);
1860         int                     rc;
1861         ENTRY;
1862
1863         LASSERT(ss != NULL);
1864         LASSERT(ss->ss_server_fld != NULL);
1865
1866         rc = osd_fld_lookup(env, osd, seq, range);
1867         if (rc != 0) {
1868                 if (rc != -ENOENT)
1869                         CERROR("%s: can't lookup FLD sequence %#llx: rc = %d\n",
1870                                osd_name(osd), seq, rc);
1871                 RETURN(0);
1872         }
1873
1874         RETURN(ss->ss_node_id == range->lsr_index);
1875 }
1876
1877 static void osd_trans_stop_cb(struct osd_thandle *oth, int result)
1878 {
1879         struct dt_txn_commit_cb *dcb;
1880         struct dt_txn_commit_cb *tmp;
1881
1882         /* call per-transaction stop callbacks if any */
1883         list_for_each_entry_safe(dcb, tmp, &oth->ot_stop_dcb_list,
1884                                  dcb_linkage) {
1885                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1886                          "commit callback entry: magic=%x name='%s'\n",
1887                          dcb->dcb_magic, dcb->dcb_name);
1888                 list_del_init(&dcb->dcb_linkage);
1889                 dcb->dcb_func(NULL, &oth->ot_super, dcb, result);
1890         }
1891 }
1892
1893 /*
1894  * Concurrency: shouldn't matter.
1895  */
1896 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
1897                           struct thandle *th)
1898 {
1899         int                     rc = 0, remove_agents = 0;
1900         struct osd_thandle     *oh;
1901         struct osd_thread_info *oti = osd_oti_get(env);
1902         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
1903         struct osd_device      *osd = osd_dt_dev(th->th_dev);
1904         struct qsd_instance    *qsd = osd->od_quota_slave;
1905         struct lquota_trans    *qtrans;
1906         ENTRY;
1907
1908         oh = container_of0(th, struct osd_thandle, ot_super);
1909
1910         remove_agents = oh->ot_remove_agents;
1911
1912         qtrans = oh->ot_quota_trans;
1913         oh->ot_quota_trans = NULL;
1914
1915         if (oh->ot_handle != NULL) {
1916                 int rc2;
1917                 handle_t *hdl = oh->ot_handle;
1918
1919                 /*
1920                  * add commit callback
1921                  * notice we don't do this in osd_trans_start()
1922                  * as underlying transaction can change during truncate
1923                  */
1924                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
1925                                          &oh->ot_jcb);
1926
1927                 LASSERT(oti->oti_txns == 1);
1928                 oti->oti_txns--;
1929
1930                 rc = dt_txn_hook_stop(env, th);
1931                 if (rc != 0)
1932                         CERROR("%s: failed in transaction hook: rc = %d\n",
1933                                osd_name(osd), rc);
1934
1935                 osd_trans_stop_cb(oh, rc);
1936                 /* hook functions might modify th_sync */
1937                 hdl->h_sync = th->th_sync;
1938
1939                 oh->ot_handle = NULL;
1940                 OSD_CHECK_SLOW_TH(oh, osd, rc2 = ldiskfs_journal_stop(hdl));
1941                 if (rc2 != 0)
1942                         CERROR("%s: failed to stop transaction: rc = %d\n",
1943                                osd_name(osd), rc2);
1944                 if (!rc)
1945                         rc = rc2;
1946         } else {
1947                 osd_trans_stop_cb(oh, th->th_result);
1948                 OBD_FREE_PTR(oh);
1949         }
1950
1951         /* inform the quota slave device that the transaction is stopping */
1952         qsd_op_end(env, qsd, qtrans);
1953
1954         /* as we want IO to journal and data IO be concurrent, we don't block
1955          * awaiting data IO completion in osd_do_bio(), instead we wait here
1956          * once transaction is submitted to the journal. all reqular requests
1957          * don't do direct IO (except read/write), thus this wait_event becomes
1958          * no-op for them.
1959          *
1960          * IMPORTANT: we have to wait till any IO submited by the thread is
1961          * completed otherwise iobuf may be corrupted by different request
1962          */
1963         wait_event(iobuf->dr_wait,
1964                        atomic_read(&iobuf->dr_numreqs) == 0);
1965         osd_fini_iobuf(osd, iobuf);
1966         if (!rc)
1967                 rc = iobuf->dr_error;
1968
1969         if (unlikely(remove_agents != 0))
1970                 osd_process_scheduled_agent_removals(env, osd);
1971
1972         oti->oti_ins_cache_depth--;
1973         /* reset OI cache for safety */
1974         if (oti->oti_ins_cache_depth == 0)
1975                 oti->oti_ins_cache_used = 0;
1976
1977         sb_end_write(osd_sb(osd));
1978
1979         RETURN(rc);
1980 }
1981
1982 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
1983 {
1984         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
1985                                                ot_super);
1986
1987         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
1988         LASSERT(&dcb->dcb_func != NULL);
1989         if (dcb->dcb_flags & DCB_TRANS_STOP)
1990                 list_add(&dcb->dcb_linkage, &oh->ot_stop_dcb_list);
1991         else
1992                 list_add(&dcb->dcb_linkage, &oh->ot_commit_dcb_list);
1993
1994         return 0;
1995 }
1996
1997 /*
1998  * Called just before object is freed. Releases all resources except for
1999  * object itself (that is released by osd_object_free()).
2000  *
2001  * Concurrency: no concurrent access is possible that late in object
2002  * life-cycle.
2003  */
2004 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
2005 {
2006         struct osd_object *obj   = osd_obj(l);
2007         struct inode      *inode = obj->oo_inode;
2008
2009         LINVRNT(osd_invariant(obj));
2010
2011         /*
2012          * If object is unlinked remove fid->ino mapping from object index.
2013          */
2014
2015         osd_index_fini(obj);
2016         if (inode != NULL) {
2017                 struct qsd_instance     *qsd = osd_obj2dev(obj)->od_quota_slave;
2018                 qid_t                    uid = i_uid_read(inode);
2019                 qid_t                    gid = i_gid_read(inode);
2020
2021                 obj->oo_inode = NULL;
2022                 iput(inode);
2023                 if (!obj->oo_header && qsd) {
2024                         struct osd_thread_info  *info = osd_oti_get(env);
2025                         struct lquota_id_info   *qi = &info->oti_qi;
2026
2027                         /* Release granted quota to master if necessary */
2028                         qi->lqi_id.qid_uid = uid;
2029                         qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
2030
2031                         qi->lqi_id.qid_uid = gid;
2032                         qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
2033
2034                         qi->lqi_id.qid_uid = i_projid_read(inode);
2035                         qsd_op_adjust(env, qsd, &qi->lqi_id, PRJQUOTA);
2036                 }
2037         }
2038 }
2039
2040 /*
2041  * Concurrency: ->loo_object_release() is called under site spin-lock.
2042  */
2043 static void osd_object_release(const struct lu_env *env,
2044                                struct lu_object *l)
2045 {
2046         struct osd_object *o = osd_obj(l);
2047         /* nobody should be releasing a non-destroyed object with nlink=0
2048          * the API allows this, but ldiskfs doesn't like and then report
2049          * this inode as deleted */
2050         if (unlikely(!o->oo_destroyed && o->oo_inode && o->oo_inode->i_nlink == 0))
2051                 LBUG();
2052 }
2053
2054 /*
2055  * Concurrency: shouldn't matter.
2056  */
2057 static int osd_object_print(const struct lu_env *env, void *cookie,
2058                             lu_printer_t p, const struct lu_object *l)
2059 {
2060         struct osd_object *o = osd_obj(l);
2061         struct iam_descr  *d;
2062
2063         if (o->oo_dir != NULL)
2064                 d = o->oo_dir->od_container.ic_descr;
2065         else
2066                 d = NULL;
2067         return (*p)(env, cookie,
2068                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
2069                     o, o->oo_inode,
2070                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
2071                     o->oo_inode ? o->oo_inode->i_generation : 0,
2072                     d ? d->id_ops->id_name : "plain");
2073 }
2074
2075 /*
2076  * Concurrency: shouldn't matter.
2077  */
2078 int osd_statfs(const struct lu_env *env, struct dt_device *d,
2079                struct obd_statfs *sfs)
2080 {
2081         struct osd_device       *osd = osd_dt_dev(d);
2082         struct super_block      *sb = osd_sb(osd);
2083         struct kstatfs          *ksfs;
2084         __u64                    reserved;
2085         int                      result = 0;
2086
2087         if (unlikely(osd->od_mnt == NULL))
2088                 return -EINPROGRESS;
2089
2090         /* osd_lproc.c call this without env, allocate ksfs for that case */
2091         if (unlikely(env == NULL)) {
2092                 OBD_ALLOC_PTR(ksfs);
2093                 if (ksfs == NULL)
2094                         return -ENOMEM;
2095         } else {
2096                 ksfs = &osd_oti_get(env)->oti_ksfs;
2097         }
2098
2099         result = sb->s_op->statfs(sb->s_root, ksfs);
2100         if (result)
2101                 goto out;
2102
2103         statfs_pack(sfs, ksfs);
2104         if (unlikely(sb->s_flags & MS_RDONLY))
2105                 sfs->os_state |= OS_STATE_READONLY;
2106         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb,
2107                                          LDISKFS_FEATURE_INCOMPAT_EXTENTS))
2108                 sfs->os_maxbytes = sb->s_maxbytes;
2109         else
2110                 sfs->os_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2111
2112         /*
2113          * Reserve some space so to avoid fragmenting the filesystem too much.
2114          * Fragmentation not only impacts performance, but can also increase
2115          * metadata overhead significantly, causing grant calculation to be
2116          * wrong.
2117          *
2118          * Reserve 0.78% of total space, at least 8MB for small filesystems.
2119          */
2120         CLASSERT(OSD_STATFS_RESERVED > LDISKFS_MAX_BLOCK_SIZE);
2121         reserved = OSD_STATFS_RESERVED >> sb->s_blocksize_bits;
2122         if (likely(sfs->os_blocks >= reserved << OSD_STATFS_RESERVED_SHIFT))
2123                 reserved = sfs->os_blocks >> OSD_STATFS_RESERVED_SHIFT;
2124
2125         sfs->os_blocks -= reserved;
2126         sfs->os_bfree  -= min(reserved, sfs->os_bfree);
2127         sfs->os_bavail -= min(reserved, sfs->os_bavail);
2128
2129 out:
2130         if (unlikely(env == NULL))
2131                 OBD_FREE_PTR(ksfs);
2132         return result;
2133 }
2134
2135 /**
2136  * Estimate space needed for file creations. We assume the largest filename
2137  * which is 2^64 - 1, hence a filename of 20 chars.
2138  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
2139  */
2140 #ifdef __LDISKFS_DIR_REC_LEN
2141 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
2142 #else
2143 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
2144 #endif
2145
2146 /*
2147  * Concurrency: doesn't access mutable data.
2148  */
2149 static void osd_conf_get(const struct lu_env *env,
2150                          const struct dt_device *dev,
2151                          struct dt_device_param *param)
2152 {
2153         struct super_block *sb = osd_sb(osd_dt_dev(dev));
2154         int                ea_overhead;
2155
2156         /*
2157          * XXX should be taken from not-yet-existing fs abstraction layer.
2158          */
2159         param->ddp_max_name_len = LDISKFS_NAME_LEN;
2160         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
2161         param->ddp_symlink_max  = sb->s_blocksize;
2162         param->ddp_mount_type     = LDD_MT_LDISKFS;
2163         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EXTENTS))
2164                 param->ddp_maxbytes = sb->s_maxbytes;
2165         else
2166                 param->ddp_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2167         /* inode are statically allocated, so per-inode space consumption
2168          * is the space consumed by the directory entry */
2169         param->ddp_inodespace     = PER_OBJ_USAGE;
2170         /* EXT_INIT_MAX_LEN is the theoretical maximum extent size  (32k blocks
2171          * = 128MB) which is unlikely to be hit in real life. Report a smaller
2172          * maximum length to not under count the actual number of extents
2173          * needed for writing a file. */
2174         param->ddp_max_extent_blks = EXT_INIT_MAX_LEN >> 2;
2175         /* worst-case extent insertion metadata overhead */
2176         param->ddp_extent_tax = 6 * LDISKFS_BLOCK_SIZE(sb);
2177         param->ddp_mntopts      = 0;
2178         if (test_opt(sb, XATTR_USER))
2179                 param->ddp_mntopts |= MNTOPT_USERXATTR;
2180         if (test_opt(sb, POSIX_ACL))
2181                 param->ddp_mntopts |= MNTOPT_ACL;
2182
2183         /* LOD might calculate the max stripe count based on max_ea_size,
2184          * so we need take account in the overhead as well,
2185          * xattr_header + magic + xattr_entry_head */
2186         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
2187                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
2188
2189 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
2190         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EA_INODE))
2191                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
2192                                                                 ea_overhead;
2193         else
2194 #endif
2195                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
2196
2197         if (param->ddp_max_ea_size > OSD_MAX_EA_SIZE)
2198                 param->ddp_max_ea_size = OSD_MAX_EA_SIZE;
2199
2200         /* Preferred RPC size for efficient disk IO.  4MB shows good
2201          * all-around performance for ldiskfs, but use bigalloc chunk size
2202          * by default if larger. */
2203 #if defined(LDISKFS_CLUSTER_SIZE)
2204         if (LDISKFS_CLUSTER_SIZE(sb) > DT_DEF_BRW_SIZE)
2205                 param->ddp_brw_size = LDISKFS_CLUSTER_SIZE(sb);
2206         else
2207 #endif
2208                 param->ddp_brw_size = DT_DEF_BRW_SIZE;
2209 }
2210
2211 /*
2212  * Concurrency: shouldn't matter.
2213  */
2214 static int osd_sync(const struct lu_env *env, struct dt_device *d)
2215 {
2216         int rc;
2217
2218         CDEBUG(D_CACHE, "%s: syncing OSD\n", osd_dt_dev(d)->od_svname);
2219
2220         rc = ldiskfs_force_commit(osd_sb(osd_dt_dev(d)));
2221
2222         CDEBUG(D_CACHE, "%s: synced OSD: rc = %d\n", osd_dt_dev(d)->od_svname,
2223                rc);
2224
2225         return rc;
2226 }
2227
2228 /**
2229  * Start commit for OSD device.
2230  *
2231  * An implementation of dt_commit_async method for OSD device.
2232  * Asychronously starts underlayng fs sync and thereby a transaction
2233  * commit.
2234  *
2235  * \param env environment
2236  * \param d dt device
2237  *
2238  * \see dt_device_operations
2239  */
2240 static int osd_commit_async(const struct lu_env *env,
2241                             struct dt_device *d)
2242 {
2243         struct super_block *s = osd_sb(osd_dt_dev(d));
2244         ENTRY;
2245
2246         CDEBUG(D_HA, "%s: async commit OSD\n", osd_dt_dev(d)->od_svname);
2247         RETURN(s->s_op->sync_fs(s, 0));
2248 }
2249
2250 /* Our own copy of the set readonly functions if present, or NU if not. */
2251 static int (*priv_dev_set_rdonly)(struct block_device *bdev);
2252 static int (*priv_dev_check_rdonly)(struct block_device *bdev);
2253 /* static int (*priv_dev_clear_rdonly)(struct block_device *bdev); */
2254
2255 /*
2256  * Concurrency: shouldn't matter.
2257  */
2258 static int osd_ro(const struct lu_env *env, struct dt_device *d)
2259 {
2260         struct super_block *sb = osd_sb(osd_dt_dev(d));
2261         struct block_device *dev = sb->s_bdev;
2262         int rc = -EOPNOTSUPP;
2263         ENTRY;
2264
2265         if (priv_dev_set_rdonly) {
2266                 struct block_device *jdev = LDISKFS_SB(sb)->journal_bdev;
2267
2268                 rc = 0;
2269                 CERROR("*** setting %s read-only ***\n",
2270                        osd_dt_dev(d)->od_svname);
2271
2272                 if (sb->s_op->freeze_fs) {
2273                         rc = sb->s_op->freeze_fs(sb);
2274                         if (rc)
2275                                 goto out;
2276                 }
2277
2278                 if (jdev && (jdev != dev)) {
2279                         CDEBUG(D_IOCTL | D_HA, "set journal dev %lx rdonly\n",
2280                                (long)jdev);
2281                         priv_dev_set_rdonly(jdev);
2282                 }
2283                 CDEBUG(D_IOCTL | D_HA, "set dev %lx rdonly\n", (long)dev);
2284                 priv_dev_set_rdonly(dev);
2285
2286                 if (sb->s_op->unfreeze_fs)
2287                         sb->s_op->unfreeze_fs(sb);
2288         }
2289
2290 out:
2291         if (rc)
2292                 CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
2293                        osd_dt_dev(d)->od_svname, (long)dev, rc);
2294
2295         RETURN(rc);
2296 }
2297
2298 /**
2299  * Note: we do not count into QUOTA here.
2300  * If we mount with --data_journal we may need more.
2301  */
2302 const int osd_dto_credits_noquota[DTO_NR] = {
2303         /**
2304          * Insert.
2305          * INDEX_EXTRA_TRANS_BLOCKS(8) +
2306          * SINGLEDATA_TRANS_BLOCKS(8)
2307          * XXX Note: maybe iam need more, since iam have more level than
2308          *           EXT3 htree.
2309          */
2310         [DTO_INDEX_INSERT]  = 16,
2311         /**
2312          * Delete
2313          * just modify a single entry, probably merge few within a block
2314          */
2315         [DTO_INDEX_DELETE]  = 1,
2316         /**
2317          * Used for OI scrub
2318          */
2319         [DTO_INDEX_UPDATE]  = 16,
2320         /**
2321          * 4(inode, inode bits, groups, GDT)
2322          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
2323          */
2324         [DTO_OBJECT_CREATE] = 4,
2325         /**
2326          * 4(inode, inode bits, groups, GDT)
2327          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
2328          */
2329         [DTO_OBJECT_DELETE] = 4,
2330         /**
2331          * Attr set credits (inode)
2332          */
2333         [DTO_ATTR_SET_BASE] = 1,
2334         /**
2335          * Xattr set. The same as xattr of EXT3.
2336          * DATA_TRANS_BLOCKS(14)
2337          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
2338          * are also counted in. Do not know why?
2339          */
2340         [DTO_XATTR_SET]     = 14,
2341         /**
2342          * credits for inode change during write.
2343          */
2344         [DTO_WRITE_BASE]    = 3,
2345         /**
2346          * credits for single block write.
2347          */
2348         [DTO_WRITE_BLOCK]   = 14,
2349         /**
2350          * Attr set credits for chown.
2351          * This is extra credits for setattr, and it is null without quota
2352          */
2353         [DTO_ATTR_SET_CHOWN] = 0
2354 };
2355
2356 static const struct dt_device_operations osd_dt_ops = {
2357         .dt_root_get       = osd_root_get,
2358         .dt_statfs         = osd_statfs,
2359         .dt_trans_create   = osd_trans_create,
2360         .dt_trans_start    = osd_trans_start,
2361         .dt_trans_stop     = osd_trans_stop,
2362         .dt_trans_cb_add   = osd_trans_cb_add,
2363         .dt_conf_get       = osd_conf_get,
2364         .dt_sync           = osd_sync,
2365         .dt_ro             = osd_ro,
2366         .dt_commit_async   = osd_commit_async,
2367 };
2368
2369 static void osd_read_lock(const struct lu_env *env, struct dt_object *dt,
2370                           unsigned role)
2371 {
2372         struct osd_object *obj = osd_dt_obj(dt);
2373         struct osd_thread_info *oti = osd_oti_get(env);
2374
2375         LINVRNT(osd_invariant(obj));
2376
2377         LASSERT(obj->oo_owner != env);
2378         down_read_nested(&obj->oo_sem, role);
2379
2380         LASSERT(obj->oo_owner == NULL);
2381         oti->oti_r_locks++;
2382 }
2383
2384 static void osd_write_lock(const struct lu_env *env, struct dt_object *dt,
2385                            unsigned role)
2386 {
2387         struct osd_object *obj = osd_dt_obj(dt);
2388         struct osd_thread_info *oti = osd_oti_get(env);
2389
2390         LINVRNT(osd_invariant(obj));
2391
2392         LASSERT(obj->oo_owner != env);
2393         down_write_nested(&obj->oo_sem, role);
2394
2395         LASSERT(obj->oo_owner == NULL);
2396         obj->oo_owner = env;
2397         oti->oti_w_locks++;
2398 }
2399
2400 static void osd_read_unlock(const struct lu_env *env, struct dt_object *dt)
2401 {
2402         struct osd_object *obj = osd_dt_obj(dt);
2403         struct osd_thread_info *oti = osd_oti_get(env);
2404
2405         LINVRNT(osd_invariant(obj));
2406
2407         LASSERT(oti->oti_r_locks > 0);
2408         oti->oti_r_locks--;
2409         up_read(&obj->oo_sem);
2410 }
2411
2412 static void osd_write_unlock(const struct lu_env *env, struct dt_object *dt)
2413 {
2414         struct osd_object *obj = osd_dt_obj(dt);
2415         struct osd_thread_info *oti = osd_oti_get(env);
2416
2417         LINVRNT(osd_invariant(obj));
2418
2419         LASSERT(obj->oo_owner == env);
2420         LASSERT(oti->oti_w_locks > 0);
2421         oti->oti_w_locks--;
2422         obj->oo_owner = NULL;
2423         up_write(&obj->oo_sem);
2424 }
2425
2426 static int osd_write_locked(const struct lu_env *env, struct dt_object *dt)
2427 {
2428         struct osd_object *obj = osd_dt_obj(dt);
2429
2430         LINVRNT(osd_invariant(obj));
2431
2432         return obj->oo_owner == env;
2433 }
2434
2435 static struct timespec *osd_inode_time(const struct lu_env *env,
2436                                        struct inode *inode, __u64 seconds)
2437 {
2438         struct osd_thread_info  *oti = osd_oti_get(env);
2439         struct timespec         *t   = &oti->oti_time;
2440
2441         t->tv_sec = seconds;
2442         t->tv_nsec = 0;
2443         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
2444         return t;
2445 }
2446
2447 static void osd_inode_getattr(const struct lu_env *env,
2448                               struct inode *inode, struct lu_attr *attr)
2449 {
2450         attr->la_valid  |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
2451                            LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
2452                            LA_PROJID | LA_FLAGS | LA_NLINK | LA_RDEV |
2453                            LA_BLKSIZE | LA_TYPE;
2454
2455         attr->la_atime   = LTIME_S(inode->i_atime);
2456         attr->la_mtime   = LTIME_S(inode->i_mtime);
2457         attr->la_ctime   = LTIME_S(inode->i_ctime);
2458         attr->la_mode    = inode->i_mode;
2459         attr->la_size    = i_size_read(inode);
2460         attr->la_blocks  = inode->i_blocks;
2461         attr->la_uid     = i_uid_read(inode);
2462         attr->la_gid     = i_gid_read(inode);
2463         attr->la_projid  = i_projid_read(inode);
2464         attr->la_flags   = ll_inode_to_ext_flags(inode->i_flags);
2465         attr->la_nlink   = inode->i_nlink;
2466         attr->la_rdev    = inode->i_rdev;
2467         attr->la_blksize = 1 << inode->i_blkbits;
2468         attr->la_blkbits = inode->i_blkbits;
2469         /*
2470          * Ext4 did not transfer inherit flags from raw inode
2471          * to inode flags, and ext4 internally test raw inode
2472          * @i_flags directly. Instead of patching ext4, we do it here.
2473          */
2474         if (LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL)
2475                 attr->la_flags |= LUSTRE_PROJINHERIT_FL;
2476 }
2477
2478 static int osd_attr_get(const struct lu_env *env,
2479                         struct dt_object *dt,
2480                         struct lu_attr *attr)
2481 {
2482         struct osd_object *obj = osd_dt_obj(dt);
2483
2484         if (unlikely(!dt_object_exists(dt)))
2485                 return -ENOENT;
2486         if (unlikely(obj->oo_destroyed))
2487                 return -ENOENT;
2488
2489         LASSERT(!dt_object_remote(dt));
2490         LINVRNT(osd_invariant(obj));
2491
2492         spin_lock(&obj->oo_guard);
2493         osd_inode_getattr(env, obj->oo_inode, attr);
2494         if (obj->oo_lma_flags & LUSTRE_ORPHAN_FL)
2495                 attr->la_flags |= LUSTRE_ORPHAN_FL;
2496         spin_unlock(&obj->oo_guard);
2497
2498         return 0;
2499 }
2500
2501 static int osd_declare_attr_qid(const struct lu_env *env,
2502                                 struct osd_object *obj,
2503                                 struct osd_thandle *oh, long long bspace,
2504                                 qid_t old_id, qid_t new_id, bool enforce,
2505                                 unsigned type, bool ignore_edquot)
2506 {
2507         int rc;
2508         struct osd_thread_info *info = osd_oti_get(env);
2509         struct lquota_id_info  *qi = &info->oti_qi;
2510
2511         qi->lqi_type = type;
2512         /* inode accounting */
2513         qi->lqi_is_blk = false;
2514
2515         /* one more inode for the new id ... */
2516         qi->lqi_id.qid_uid = new_id;
2517         qi->lqi_space      = 1;
2518         /* Reserve credits for the new id */
2519         rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
2520         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2521                 rc = 0;
2522         if (rc)
2523                 RETURN(rc);
2524
2525         /* and one less inode for the current id */
2526         qi->lqi_id.qid_uid = old_id;
2527         qi->lqi_space      = -1;
2528         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2529         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2530                 rc = 0;
2531         if (rc)
2532                 RETURN(rc);
2533
2534         /* block accounting */
2535         qi->lqi_is_blk = true;
2536
2537         /* more blocks for the new id ... */
2538         qi->lqi_id.qid_uid = new_id;
2539         qi->lqi_space      = bspace;
2540         /*
2541          * Credits for the new uid has been reserved, re-use "obj"
2542          * to save credit reservation.
2543          */
2544         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2545         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2546                 rc = 0;
2547         if (rc)
2548                 RETURN(rc);
2549
2550         /* and finally less blocks for the current uid */
2551         qi->lqi_id.qid_uid = old_id;
2552         qi->lqi_space      = -bspace;
2553         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2554         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2555                 rc = 0;
2556
2557         RETURN(rc);
2558 }
2559
2560 static int osd_declare_attr_set(const struct lu_env *env,
2561                                 struct dt_object *dt,
2562                                 const struct lu_attr *attr,
2563                                 struct thandle *handle)
2564 {
2565         struct osd_thandle     *oh;
2566         struct osd_object      *obj;
2567         qid_t                   uid;
2568         qid_t                   gid;
2569         long long               bspace;
2570         int                     rc = 0;
2571         bool                    enforce;
2572         ENTRY;
2573
2574         LASSERT(dt != NULL);
2575         LASSERT(handle != NULL);
2576
2577         obj = osd_dt_obj(dt);
2578         LASSERT(osd_invariant(obj));
2579
2580         oh = container_of0(handle, struct osd_thandle, ot_super);
2581         LASSERT(oh->ot_handle == NULL);
2582
2583         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
2584                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2585
2586         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2587                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2588
2589         if (attr == NULL || obj->oo_inode == NULL)
2590                 RETURN(rc);
2591
2592         bspace   = obj->oo_inode->i_blocks << 9;
2593         bspace   = toqb(bspace);
2594
2595         /* Changing ownership is always preformed by super user, it should not
2596          * fail with EDQUOT unless required explicitly.
2597          *
2598          * We still need to call the osd_declare_qid() to calculate the journal
2599          * credits for updating quota accounting files and to trigger quota
2600          * space adjustment once the operation is completed.*/
2601         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
2602                 bool ignore_edquot = !(attr->la_flags & LUSTRE_SET_SYNC_FL);
2603
2604                 if (!ignore_edquot)
2605                         CDEBUG(D_QUOTA, "%s: enforce quota on UID %u, GID %u"
2606                                "(the quota space is %lld)\n",
2607                                obj->oo_inode->i_sb->s_id, attr->la_uid,
2608                                attr->la_gid, bspace);
2609
2610                 /* USERQUOTA */
2611                 uid = i_uid_read(obj->oo_inode);
2612                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
2613                 rc = osd_declare_attr_qid(env, obj, oh, bspace, uid,
2614                                           attr->la_uid, enforce, USRQUOTA,
2615                                           true);
2616                 if (rc)
2617                         RETURN(rc);
2618
2619                 gid = i_gid_read(obj->oo_inode);
2620                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
2621                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2622                                           i_gid_read(obj->oo_inode),
2623                                           attr->la_gid, enforce, GRPQUOTA,
2624                                           ignore_edquot);
2625                 if (rc)
2626                         RETURN(rc);
2627
2628         }
2629 #ifdef HAVE_PROJECT_QUOTA
2630         if (attr->la_valid & LA_PROJID) {
2631                 __u32 projid = i_projid_read(obj->oo_inode);
2632                 enforce = (attr->la_valid & LA_PROJID) &&
2633                                         (attr->la_projid != projid);
2634                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2635                                           (qid_t)projid, (qid_t)attr->la_projid,
2636                                           enforce, PRJQUOTA, true);
2637                 if (rc)
2638                         RETURN(rc);
2639         }
2640 #endif
2641         RETURN(rc);
2642 }
2643
2644 static int osd_inode_setattr(const struct lu_env *env,
2645                              struct inode *inode, const struct lu_attr *attr)
2646 {
2647         __u64 bits = attr->la_valid;
2648
2649         /* Only allow set size for regular file */
2650         if (!S_ISREG(inode->i_mode))
2651                 bits &= ~(LA_SIZE | LA_BLOCKS);
2652
2653         if (bits == 0)
2654                 return 0;
2655
2656         if (bits & LA_ATIME)
2657                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
2658         if (bits & LA_CTIME)
2659                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
2660         if (bits & LA_MTIME)
2661                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
2662         if (bits & LA_SIZE) {
2663                 spin_lock(&inode->i_lock);
2664                 LDISKFS_I(inode)->i_disksize = attr->la_size;
2665                 i_size_write(inode, attr->la_size);
2666                 spin_unlock(&inode->i_lock);
2667         }
2668
2669         /* OSD should not change "i_blocks" which is used by quota.
2670          * "i_blocks" should be changed by ldiskfs only. */
2671         if (bits & LA_MODE)
2672                 inode->i_mode = (inode->i_mode & S_IFMT) |
2673                                 (attr->la_mode & ~S_IFMT);
2674         if (bits & LA_UID)
2675                 i_uid_write(inode, attr->la_uid);
2676         if (bits & LA_GID)
2677                 i_gid_write(inode, attr->la_gid);
2678         if (bits & LA_PROJID)
2679                 i_projid_write(inode, attr->la_projid);
2680         if (bits & LA_NLINK)
2681                 set_nlink(inode, attr->la_nlink);
2682         if (bits & LA_RDEV)
2683                 inode->i_rdev = attr->la_rdev;
2684
2685         if (bits & LA_FLAGS) {
2686                 /* always keep S_NOCMTIME */
2687                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
2688                                  S_NOCMTIME;
2689                 /*
2690                  * Ext4 did not transfer inherit flags from
2691                  * @inode->i_flags to raw inode i_flags when writing
2692                  * flags, we do it explictly here.
2693                  */
2694                 if (attr->la_flags & LUSTRE_PROJINHERIT_FL)
2695                         LDISKFS_I(inode)->i_flags |= LUSTRE_PROJINHERIT_FL;
2696                 else
2697                         LDISKFS_I(inode)->i_flags &= ~LUSTRE_PROJINHERIT_FL;
2698         }
2699         return 0;
2700 }
2701
2702 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
2703 {
2704         int rc;
2705
2706         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
2707             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
2708                 struct iattr    iattr;
2709
2710                 ll_vfs_dq_init(inode);
2711                 iattr.ia_valid = 0;
2712                 if (attr->la_valid & LA_UID)
2713                         iattr.ia_valid |= ATTR_UID;
2714                 if (attr->la_valid & LA_GID)
2715                         iattr.ia_valid |= ATTR_GID;
2716                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
2717                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
2718
2719                 rc = ll_vfs_dq_transfer(inode, &iattr);
2720                 if (rc) {
2721                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
2722                                "enforcement enabled on the ldiskfs "
2723                                "filesystem?\n", inode->i_sb->s_id, rc);
2724                         return rc;
2725                 }
2726         }
2727
2728         /* Handle project id transfer here properly */
2729         if (attr->la_valid & LA_PROJID &&
2730             attr->la_projid != i_projid_read(inode)) {
2731 #ifdef HAVE_PROJECT_QUOTA
2732                 rc = ldiskfs_transfer_project(inode, attr->la_projid);
2733 #else
2734                 rc = -ENOTSUPP;
2735 #endif
2736                 if (rc) {
2737                         CERROR("%s: quota transfer failed: rc = %d. Is project "
2738                                "enforcement enabled on the ldiskfs "
2739                                "filesystem?\n", inode->i_sb->s_id, rc);
2740                         return rc;
2741                 }
2742         }
2743         return 0;
2744 }
2745
2746 static int osd_attr_set(const struct lu_env *env,
2747                         struct dt_object *dt,
2748                         const struct lu_attr *attr,
2749                         struct thandle *handle)
2750 {
2751         struct osd_object *obj = osd_dt_obj(dt);
2752         struct inode      *inode;
2753         int rc;
2754
2755         if (!dt_object_exists(dt))
2756                 return -ENOENT;
2757
2758         LASSERT(handle != NULL);
2759         LASSERT(!dt_object_remote(dt));
2760         LASSERT(osd_invariant(obj));
2761
2762         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
2763
2764         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING) &&
2765             !osd_obj2dev(obj)->od_is_ost) {
2766                 struct osd_thread_info  *oti  = osd_oti_get(env);
2767                 const struct lu_fid     *fid0 = lu_object_fid(&dt->do_lu);
2768                 struct lu_fid           *fid1 = &oti->oti_fid;
2769                 struct osd_inode_id     *id   = &oti->oti_id;
2770                 struct iam_path_descr   *ipd;
2771                 struct iam_container    *bag;
2772                 struct osd_thandle      *oh;
2773                 int                      rc;
2774
2775                 fid_cpu_to_be(fid1, fid0);
2776                 memset(id, 1, sizeof(*id));
2777                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
2778                                   fid0)->oi_dir.od_container;
2779                 ipd = osd_idx_ipd_get(env, bag);
2780                 if (unlikely(ipd == NULL))
2781                         RETURN(-ENOMEM);
2782
2783                 oh = container_of0(handle, struct osd_thandle, ot_super);
2784                 rc = iam_update(oh->ot_handle, bag, (const struct iam_key *)fid1,
2785                                 (const struct iam_rec *)id, ipd);
2786                 osd_ipd_put(env, bag, ipd);
2787                 return(rc > 0 ? 0 : rc);
2788         }
2789
2790         inode = obj->oo_inode;
2791
2792         rc = osd_quota_transfer(inode, attr);
2793         if (rc)
2794                 return rc;
2795
2796         spin_lock(&obj->oo_guard);
2797         rc = osd_inode_setattr(env, inode, attr);
2798         spin_unlock(&obj->oo_guard);
2799         if (rc != 0)
2800                 GOTO(out, rc);
2801
2802         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2803
2804         if (!(attr->la_valid & LA_FLAGS))
2805                 GOTO(out, rc);
2806
2807         /* Let's check if there are extra flags need to be set into LMA */
2808         if (attr->la_flags & LUSTRE_LMA_FL_MASKS) {
2809                 struct osd_thread_info *info = osd_oti_get(env);
2810                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
2811
2812                 LASSERT(!obj->oo_pfid_in_lma);
2813
2814                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
2815                                  &info->oti_ost_attrs);
2816                 if (rc)
2817                         GOTO(out, rc);
2818
2819                 lma->lma_incompat |=
2820                         lustre_to_lma_flags(attr->la_flags);
2821                 lustre_lma_swab(lma);
2822                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA,
2823                                      lma, sizeof(*lma), XATTR_REPLACE);
2824                 if (rc != 0) {
2825                         struct osd_device *osd = osd_obj2dev(obj);
2826
2827                         CWARN("%s: set "DFID" lma flags %u failed: rc = %d\n",
2828                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
2829                               lma->lma_incompat, rc);
2830                 } else {
2831                         obj->oo_lma_flags =
2832                                 attr->la_flags & LUSTRE_LMA_FL_MASKS;
2833                 }
2834                 osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
2835         }
2836 out:
2837         osd_trans_exec_check(env, handle, OSD_OT_ATTR_SET);
2838
2839         return rc;
2840 }
2841
2842 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
2843                                            struct osd_object *obj,
2844                                            const char *name, const int namelen)
2845 {
2846         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
2847 }
2848
2849 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
2850                       umode_t mode, struct dt_allocation_hint *hint,
2851                       struct thandle *th)
2852 {
2853         int result;
2854         struct osd_device  *osd = osd_obj2dev(obj);
2855         struct osd_thandle *oth;
2856         struct dt_object   *parent = NULL;
2857         struct inode       *inode;
2858
2859         LINVRNT(osd_invariant(obj));
2860         LASSERT(obj->oo_inode == NULL);
2861         LASSERT(obj->oo_hl_head == NULL);
2862
2863         if (S_ISDIR(mode) && ldiskfs_pdo) {
2864                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
2865                 if (obj->oo_hl_head == NULL)
2866                         return -ENOMEM;
2867         }
2868
2869         oth = container_of(th, struct osd_thandle, ot_super);
2870         LASSERT(oth->ot_handle->h_transaction != NULL);
2871
2872         if (hint != NULL && hint->dah_parent != NULL &&
2873             !dt_object_remote(hint->dah_parent))
2874                 parent = hint->dah_parent;
2875
2876         inode = ldiskfs_create_inode(oth->ot_handle,
2877                                      parent ? osd_dt_obj(parent)->oo_inode :
2878                                               osd_sb(osd)->s_root->d_inode,
2879                                      mode);
2880         if (!IS_ERR(inode)) {
2881                 /* Do not update file c/mtime in ldiskfs. */
2882                 inode->i_flags |= S_NOCMTIME;
2883
2884                 /* For new created object, it must be consistent,
2885                  * and it is unnecessary to scrub against it. */
2886                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
2887
2888                 obj->oo_inode = inode;
2889                 result = 0;
2890         } else {
2891                 if (obj->oo_hl_head != NULL) {
2892                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
2893                         obj->oo_hl_head = NULL;
2894                 }
2895                 result = PTR_ERR(inode);
2896         }
2897         LINVRNT(osd_invariant(obj));
2898         return result;
2899 }
2900
2901 enum {
2902         OSD_NAME_LEN = 255
2903 };
2904
2905 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
2906                      struct lu_attr *attr,
2907                      struct dt_allocation_hint *hint,
2908                      struct dt_object_format *dof,
2909                      struct thandle *th)
2910 {
2911         int result;
2912         struct osd_thandle *oth;
2913         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX | S_ISGID));
2914
2915         LASSERT(S_ISDIR(attr->la_mode));
2916
2917         oth = container_of(th, struct osd_thandle, ot_super);
2918         LASSERT(oth->ot_handle->h_transaction != NULL);
2919         result = osd_mkfile(info, obj, mode, hint, th);
2920
2921         return result;
2922 }
2923
2924 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
2925                         struct lu_attr *attr,
2926                         struct dt_allocation_hint *hint,
2927                         struct dt_object_format *dof,
2928                         struct thandle *th)
2929 {
2930         int result;
2931         struct osd_thandle *oth;
2932         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
2933
2934         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
2935
2936         LASSERT(S_ISREG(attr->la_mode));
2937
2938         oth = container_of(th, struct osd_thandle, ot_super);
2939         LASSERT(oth->ot_handle->h_transaction != NULL);
2940
2941         result = osd_mkfile(info, obj, mode, hint, th);
2942         if (result == 0) {
2943                 LASSERT(obj->oo_inode != NULL);
2944                 if (feat->dif_flags & DT_IND_VARKEY)
2945                         result = iam_lvar_create(obj->oo_inode,
2946                                                  feat->dif_keysize_max,
2947                                                  feat->dif_ptrsize,
2948                                                  feat->dif_recsize_max,
2949                                                  oth->ot_handle);
2950                 else
2951                         result = iam_lfix_create(obj->oo_inode,
2952                                                  feat->dif_keysize_max,
2953                                                  feat->dif_ptrsize,
2954                                                  feat->dif_recsize_max,
2955                                                  oth->ot_handle);
2956
2957         }
2958         return result;
2959 }
2960
2961 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
2962                      struct lu_attr *attr,
2963                      struct dt_allocation_hint *hint,
2964                      struct dt_object_format *dof,
2965                      struct thandle *th)
2966 {
2967         LASSERT(S_ISREG(attr->la_mode));
2968         return osd_mkfile(info, obj, (attr->la_mode &
2969                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2970 }
2971
2972 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
2973                      struct lu_attr *attr,
2974                      struct dt_allocation_hint *hint,
2975                      struct dt_object_format *dof,
2976                      struct thandle *th)
2977 {
2978         LASSERT(S_ISLNK(attr->la_mode));
2979         return osd_mkfile(info, obj, (attr->la_mode &
2980                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2981 }
2982
2983 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
2984                      struct lu_attr *attr,
2985                      struct dt_allocation_hint *hint,
2986                      struct dt_object_format *dof,
2987                      struct thandle *th)
2988 {
2989         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
2990         int result;
2991
2992         LINVRNT(osd_invariant(obj));
2993         LASSERT(obj->oo_inode == NULL);
2994         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
2995                 S_ISFIFO(mode) || S_ISSOCK(mode));
2996
2997         result = osd_mkfile(info, obj, mode, hint, th);
2998         if (result == 0) {
2999                 LASSERT(obj->oo_inode != NULL);
3000                 /*
3001                  * This inode should be marked dirty for i_rdev.  Currently
3002                  * that is done in the osd_attr_init().
3003                  */
3004                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
3005                                    attr->la_rdev);
3006         }
3007         LINVRNT(osd_invariant(obj));
3008         return result;
3009 }
3010
3011 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
3012                               struct lu_attr *,
3013                               struct dt_allocation_hint *hint,
3014                               struct dt_object_format *dof,
3015                               struct thandle *);
3016
3017 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
3018 {
3019         osd_obj_type_f result;
3020
3021         switch (type) {
3022         case DFT_DIR:
3023                 result = osd_mkdir;
3024                 break;
3025         case DFT_REGULAR:
3026                 result = osd_mkreg;
3027                 break;
3028         case DFT_SYM:
3029                 result = osd_mksym;
3030                 break;
3031         case DFT_NODE:
3032                 result = osd_mknod;
3033                 break;
3034         case DFT_INDEX:
3035                 result = osd_mk_index;
3036                 break;
3037
3038         default:
3039                 LBUG();
3040                 break;
3041         }
3042         return result;
3043 }
3044
3045
3046 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
3047                         struct dt_object *parent, struct dt_object *child,
3048                         umode_t child_mode)
3049 {
3050         LASSERT(ah);
3051
3052         ah->dah_parent = parent;
3053         ah->dah_mode = child_mode;
3054
3055         if (parent != NULL && !dt_object_remote(parent)) {
3056                 /* will help to find FID->ino at dt_insert("..") */
3057                 struct osd_object *pobj = osd_dt_obj(parent);
3058                 osd_idc_find_and_init(env, osd_obj2dev(pobj), pobj);
3059         }
3060 }
3061
3062 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
3063                           struct lu_attr *attr, struct dt_object_format *dof)
3064 {
3065         struct inode   *inode = obj->oo_inode;
3066         __u64           valid = attr->la_valid;
3067         int             result;
3068
3069         attr->la_valid &= ~(LA_TYPE | LA_MODE);
3070
3071         if (dof->dof_type != DFT_NODE)
3072                 attr->la_valid &= ~LA_RDEV;
3073         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
3074                 attr->la_valid &= ~LA_ATIME;
3075         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
3076                 attr->la_valid &= ~LA_CTIME;
3077         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
3078                 attr->la_valid &= ~LA_MTIME;
3079
3080         result = osd_quota_transfer(inode, attr);
3081         if (result)
3082                 return;
3083
3084         if (attr->la_valid != 0) {
3085                 result = osd_inode_setattr(info->oti_env, inode, attr);
3086                 /*
3087                  * The osd_inode_setattr() should always succeed here.  The
3088                  * only error that could be returned is EDQUOT when we are
3089                  * trying to change the UID or GID of the inode. However, this
3090                  * should not happen since quota enforcement is no longer
3091                  * enabled on ldiskfs (lquota takes care of it).
3092                  */
3093                 LASSERTF(result == 0, "%d\n", result);
3094                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3095         }
3096
3097         attr->la_valid = valid;
3098 }
3099
3100 /**
3101  * Helper function for osd_create()
3102  *
3103  * \retval 0, on success
3104  */
3105 static int __osd_create(struct osd_thread_info *info, struct osd_object *obj,
3106                         struct lu_attr *attr, struct dt_allocation_hint *hint,
3107                         struct dt_object_format *dof, struct thandle *th)
3108 {
3109         int     result;
3110         __u32   umask;
3111
3112         osd_trans_exec_op(info->oti_env, th, OSD_OT_CREATE);
3113
3114         /* we drop umask so that permissions we pass are not affected */
3115         umask = current->fs->umask;
3116         current->fs->umask = 0;
3117
3118         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
3119                                                   th);
3120         if (likely(obj->oo_inode != NULL)) {
3121                 LASSERT(obj->oo_inode->i_state & I_NEW);
3122
3123                 /* Unlock the inode before attr initialization to avoid
3124                  * unnecessary dqget operations. LU-6378 */
3125                 unlock_new_inode(obj->oo_inode);
3126         }
3127
3128         if (likely(result == 0)) {
3129                 osd_attr_init(info, obj, attr, dof);
3130                 osd_object_init0(obj);
3131         }
3132
3133         /* restore previous umask value */
3134         current->fs->umask = umask;
3135
3136         osd_trans_exec_check(info->oti_env, th, OSD_OT_CREATE);
3137
3138         return result;
3139 }
3140
3141 /**
3142  * Helper function for osd_create()
3143  *
3144  * \retval 0, on success
3145  */
3146 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
3147                            const struct lu_fid *fid, struct thandle *th)
3148 {
3149         struct osd_thread_info *info = osd_oti_get(env);
3150         struct osd_inode_id    *id   = &info->oti_id;
3151         struct osd_device      *osd  = osd_obj2dev(obj);
3152         struct osd_thandle     *oh;
3153         int                     rc;
3154
3155         LASSERT(obj->oo_inode != NULL);
3156
3157         oh = container_of0(th, struct osd_thandle, ot_super);
3158         LASSERT(oh->ot_handle);
3159         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3160
3161         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
3162         rc = osd_oi_insert(info, osd, fid, id, oh->ot_handle,
3163                            OI_CHECK_FLD, NULL);
3164         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3165
3166         return rc;
3167 }
3168
3169 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
3170                    u64 seq, struct lu_seq_range *range)
3171 {
3172         struct seq_server_site  *ss = osd_seq_site(osd);
3173
3174         if (fid_seq_is_idif(seq)) {
3175                 fld_range_set_ost(range);
3176                 range->lsr_index = idif_ost_idx(seq);
3177                 return 0;
3178         }
3179
3180         if (!fid_seq_in_fldb(seq)) {
3181                 fld_range_set_mdt(range);
3182                 if (ss != NULL)
3183                         /* FIXME: If ss is NULL, it suppose not get lsr_index
3184                          * at all */
3185                         range->lsr_index = ss->ss_node_id;
3186                 return 0;
3187         }
3188
3189         LASSERT(ss != NULL);
3190         fld_range_set_any(range);
3191         /* OSD will only do local fld lookup */
3192         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
3193 }
3194
3195 static int osd_declare_create(const struct lu_env *env, struct dt_object *dt,
3196                               struct lu_attr *attr,
3197                               struct dt_allocation_hint *hint,
3198                               struct dt_object_format *dof,
3199                               struct thandle *handle)
3200 {
3201         struct osd_thandle *oh;
3202         int rc;
3203         ENTRY;
3204
3205         LASSERT(handle != NULL);
3206
3207         oh = container_of0(handle, struct osd_thandle, ot_super);
3208         LASSERT(oh->ot_handle == NULL);
3209
3210         /* EA object consumes more credits than regular object: osd_mk_index
3211          * vs. osd_mkreg: osd_mk_index will create 2 blocks for root_node and
3212          * leaf_node, could involves the block, block bitmap, groups, GDT
3213          * change for each block, so add 4 * 2 credits in that case. */
3214         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
3215                              osd_dto_credits_noquota[DTO_OBJECT_CREATE] +
3216                              (dof->dof_type == DFT_INDEX) ? 4 * 2 : 0);
3217         /* Reuse idle OI block may cause additional one OI block
3218          * to be changed. */
3219         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3220                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3221
3222         if (!attr)
3223                 RETURN(0);
3224
3225         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid,
3226                                    attr->la_projid, 1, oh, osd_dt_obj(dt),
3227                                    NULL, OSD_QID_INODE);
3228         if (rc != 0)
3229                 RETURN(rc);
3230
3231         /* will help to find FID->ino mapping at dt_insert() */
3232         rc = osd_idc_find_and_init(env, osd_obj2dev(osd_dt_obj(dt)),
3233                                    osd_dt_obj(dt));
3234
3235         RETURN(rc);
3236 }
3237
3238 /**
3239  * Called to destroy on-disk representation of the object
3240  *
3241  * Concurrency: must be locked
3242  */
3243 static int osd_declare_destroy(const struct lu_env *env, struct dt_object *dt,
3244                                struct thandle *th)
3245 {
3246         struct osd_object  *obj = osd_dt_obj(dt);
3247         struct inode       *inode = obj->oo_inode;
3248         struct osd_thandle *oh;
3249         int                 rc;
3250         ENTRY;
3251
3252         if (inode == NULL)
3253                 RETURN(-ENOENT);
3254
3255         oh = container_of0(th, struct osd_thandle, ot_super);
3256         LASSERT(oh->ot_handle == NULL);
3257
3258         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
3259                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
3260
3261         /* For removing agent entry */
3262         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu))
3263                 oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
3264
3265         /* Recycle idle OI leaf may cause additional three OI blocks
3266          * to be changed. */
3267         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3268                 osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3269                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
3270         /* one less inode */
3271         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3272                                    i_projid_read(inode), -1, oh, obj, NULL,
3273                                    OSD_QID_INODE);
3274         if (rc)
3275                 RETURN(rc);
3276         /* data to be truncated */
3277         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3278                                    i_projid_read(inode), 0, oh, obj, NULL,
3279                                    OSD_QID_BLK);
3280         if (rc)
3281                 RETURN(rc);
3282
3283         /* will help to find FID->ino when this object is being
3284          * added to PENDING/ */
3285         rc = osd_idc_find_and_init(env, osd_obj2dev(obj), obj);
3286
3287         RETURN(rc);
3288 }
3289
3290 static int osd_destroy(const struct lu_env *env, struct dt_object *dt,
3291                        struct thandle *th)
3292 {
3293         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3294         struct osd_object *obj = osd_dt_obj(dt);
3295         struct inode *inode = obj->oo_inode;
3296         struct osd_device *osd = osd_obj2dev(obj);
3297         struct osd_thandle *oh;
3298         int result;
3299         ENTRY;
3300
3301         oh = container_of0(th, struct osd_thandle, ot_super);
3302         LASSERT(oh->ot_handle);
3303         LASSERT(inode);
3304         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
3305
3306         if (unlikely(fid_is_acct(fid)))
3307                 RETURN(-EPERM);
3308
3309         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu)) {
3310                 result = osd_delete_from_remote_parent(env, osd, obj, oh, true);
3311                 if (result != 0)
3312                         CERROR("%s: remove agent entry "DFID": rc = %d\n",
3313                                osd_name(osd), PFID(fid), result);
3314         }
3315
3316         if (S_ISDIR(inode->i_mode)) {
3317                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1 ||
3318                         inode->i_nlink == 2);
3319
3320                 spin_lock(&obj->oo_guard);
3321                 clear_nlink(inode);
3322                 spin_unlock(&obj->oo_guard);
3323                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3324         }
3325
3326         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
3327
3328         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
3329
3330         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3331                 result = osd_oi_delete(osd_oti_get(env), osd, fid,
3332                                        oh->ot_handle, OI_CHECK_FLD);
3333
3334         osd_trans_exec_check(env, th, OSD_OT_DESTROY);
3335         /* XXX: add to ext3 orphan list */
3336         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
3337
3338         /* not needed in the cache anymore */
3339         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
3340         obj->oo_destroyed = 1;
3341
3342         RETURN(0);
3343 }
3344
3345 /**
3346  * Put the fid into lustre_mdt_attrs, and then place the structure
3347  * inode's ea. This fid should not be altered during the life time
3348  * of the inode.
3349  *
3350  * \retval +ve, on success
3351  * \retval -ve, on error
3352  *
3353  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
3354  */
3355 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
3356                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
3357 {
3358         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
3359         struct lustre_mdt_attrs *lma = &loa->loa_lma;
3360         int rc;
3361         ENTRY;
3362
3363         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
3364                 RETURN(0);
3365
3366         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_OST_EA_FID_SET))
3367                 rc = -ENOMEM;
3368
3369         lustre_loa_init(loa, fid, compat, incompat);
3370         lustre_loa_swab(loa, false);
3371
3372         /* For the OST device with 256 bytes inode size by default,
3373          * the PFID EA will be stored together with LMA EA to avoid
3374          * performance trouble. Otherwise the PFID EA can be stored
3375          * independently. LU-8998 */
3376         if ((compat & LMAC_FID_ON_OST) &&
3377             LDISKFS_INODE_SIZE(inode->i_sb) <= 256)
3378                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3379                                      sizeof(*loa), XATTR_CREATE);
3380         else
3381                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3382                                      sizeof(*lma), XATTR_CREATE);
3383         /* LMA may already exist, but we need to check that all the
3384          * desired compat/incompat flags have been added. */
3385         if (unlikely(rc == -EEXIST)) {
3386                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
3387                                      XATTR_NAME_LMA, (void *)loa, sizeof(*loa));
3388                 if (rc < 0)
3389                         RETURN(rc);
3390
3391                 if (rc < sizeof(*lma))
3392                         RETURN(-EINVAL);
3393
3394                 lustre_loa_swab(loa, true);
3395                 if (lu_fid_eq(fid, &lma->lma_self_fid) &&
3396                     ((compat == 0 && incompat == 0) ||
3397                      (!(~lma->lma_compat & compat) &&
3398                       !(~lma->lma_incompat & incompat))))
3399                         RETURN(0);
3400
3401                 lma->lma_self_fid = *fid;
3402                 lma->lma_compat |= compat;
3403                 lma->lma_incompat |= incompat;
3404                 if (rc == sizeof(*lma)) {
3405                         lustre_lma_swab(lma);
3406                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3407                                              sizeof(*lma), XATTR_REPLACE);
3408                 } else {
3409                         lustre_loa_swab(loa, false);
3410                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3411                                              sizeof(*loa), XATTR_REPLACE);
3412                 }
3413         }
3414
3415         RETURN(rc);
3416 }
3417
3418 /**
3419  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
3420  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
3421  * To have compatilibility with 1.8 ldiskfs driver we need to have
3422  * magic number at start of fid data.
3423  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
3424  * its inmemory API.
3425  */
3426 static void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
3427                                          const struct lu_fid *fid)
3428 {
3429         if (!fid_is_namespace_visible(fid) ||
3430             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
3431                 param->edp_magic = 0;
3432                 return;
3433         }
3434
3435         param->edp_magic = LDISKFS_LUFID_MAGIC;
3436         param->edp_len =  sizeof(struct lu_fid) + 1;
3437         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
3438 }
3439
3440 /**
3441  * Try to read the fid from inode ea into dt_rec.
3442  *
3443  * \param fid object fid.
3444  *
3445  * \retval 0 on success
3446  */
3447 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
3448                           __u32 ino, struct lu_fid *fid,
3449                           struct osd_inode_id *id)
3450 {
3451         struct osd_thread_info *info  = osd_oti_get(env);
3452         struct inode           *inode;
3453         ENTRY;
3454
3455         osd_id_gen(id, ino, OSD_OII_NOGEN);
3456         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
3457         if (IS_ERR(inode))
3458                 RETURN(PTR_ERR(inode));
3459
3460         iput(inode);
3461         RETURN(0);
3462 }
3463
3464 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
3465                                         struct inode *dir,
3466                                         struct inode *parent_dir,
3467                                         const struct lu_fid *dot_fid,
3468                                         const struct lu_fid *dot_dot_fid,
3469                                         struct osd_thandle *oth)
3470 {
3471         struct ldiskfs_dentry_param *dot_ldp;
3472         struct ldiskfs_dentry_param *dot_dot_ldp;
3473         __u32 saved_nlink = dir->i_nlink;
3474         int rc;
3475
3476         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
3477         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
3478
3479         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3480         dot_ldp->edp_magic = 0;
3481
3482         rc = ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
3483                                     dir, dot_ldp, dot_dot_ldp);
3484         /* The ldiskfs_add_dot_dotdot() may dir->i_nlink as 2, then
3485          * the subseqent ref_add() will increase the dir->i_nlink
3486          * as 3. That is incorrect for new created directory.
3487          *
3488          * It looks like hack, because we want to make the OSD API
3489          * to be order-independent for new created directory object
3490          * between dt_insert(..) and ref_add() operations.
3491          *
3492          * Here, we only restore the in-RAM dir-inode's nlink attr,
3493          * becuase if the nlink attr is not 2, then there will be
3494          * ref_add() called following the dt_insert(..), such call
3495          * will make both the in-RAM and on-disk dir-inode's nlink
3496          * attr to be set as 2. LU-7447 */
3497         set_nlink(dir, saved_nlink);
3498         return rc;
3499 }
3500
3501 /**
3502  * Create an local agent inode for remote entry
3503  */
3504 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
3505                                                   struct osd_device *osd,
3506                                                   struct osd_object *pobj,
3507                                                   const struct lu_fid *fid,
3508                                                   __u32 type,
3509                                                   struct thandle *th)
3510 {
3511         struct osd_thread_info  *info = osd_oti_get(env);
3512         struct inode            *local;
3513         struct osd_thandle      *oh;
3514         int                     rc;
3515         ENTRY;
3516
3517         LASSERT(th);
3518         oh = container_of(th, struct osd_thandle, ot_super);
3519         LASSERT(oh->ot_handle->h_transaction != NULL);
3520
3521         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, type);
3522         if (IS_ERR(local)) {
3523                 CERROR("%s: create local error %d\n", osd_name(osd),
3524                        (int)PTR_ERR(local));
3525                 RETURN(local);
3526         }
3527
3528         /* restore i_gid in case S_ISGID is set, we will inherit S_ISGID and set
3529          * correct gid on remote file, not agent here */
3530         local->i_gid = current_fsgid();
3531         ldiskfs_set_inode_state(local, LDISKFS_STATE_LUSTRE_NOSCRUB);
3532         unlock_new_inode(local);
3533
3534         /* Agent inode should not have project ID */
3535 #ifdef  HAVE_PROJECT_QUOTA
3536         if (LDISKFS_I(pobj->oo_inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
3537             i_projid_read(pobj->oo_inode) != 0) {
3538                 rc = ldiskfs_transfer_project(local, 0);
3539                 if (rc) {
3540                         CERROR("%s: quota transfer failed: rc = %d. Is project "
3541                                "quota enforcement enabled on the ldiskfs "
3542                                "filesystem?\n", local->i_sb->s_id, rc);
3543                         RETURN(ERR_PTR(rc));
3544                 }
3545         }
3546 #endif
3547         /* Set special LMA flag for local agent inode */
3548         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
3549         if (rc != 0) {
3550                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
3551                        osd_name(osd), PFID(fid), rc);
3552                 RETURN(ERR_PTR(rc));
3553         }
3554
3555         if (!S_ISDIR(type))
3556                 RETURN(local);
3557
3558         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
3559                                          lu_object_fid(&pobj->oo_dt.do_lu),
3560                                          fid, oh);
3561         if (rc != 0) {
3562                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
3563                         osd_name(osd), PFID(fid), rc);
3564                 RETURN(ERR_PTR(rc));
3565         }
3566
3567         RETURN(local);
3568 }
3569
3570 /**
3571  * when direntry is deleted, we have to take care of possible agent inode
3572  * referenced by that. unfortunately we can't do this at that point:
3573  * iget() within a running transaction leads to deadlock and we better do
3574  * not call that every delete declaration to save performance. so we put
3575  * a potention agent inode on a list and process that once the transaction
3576  * is over. Notice it's not any worse in terms of real orphans as regular
3577  * object destroy doesn't put inodes on the on-disk orphan list. this should
3578  * be addressed separately
3579  */
3580 static int osd_schedule_agent_inode_removal(const struct lu_env *env,
3581                                             struct osd_thandle *oh,
3582                                             __u32 ino)
3583 {
3584         struct osd_device      *osd = osd_dt_dev(oh->ot_super.th_dev);
3585         struct osd_obj_orphan *oor;
3586
3587         OBD_ALLOC_PTR(oor);
3588         if (oor == NULL)
3589                 return -ENOMEM;
3590
3591         oor->oor_ino = ino;
3592         oor->oor_env = (struct lu_env *)env;
3593         spin_lock(&osd->od_osfs_lock);
3594         list_add(&oor->oor_list, &osd->od_orphan_list);
3595         spin_unlock(&osd->od_osfs_lock);
3596
3597         oh->ot_remove_agents = 1;
3598
3599         return 0;
3600
3601 }
3602
3603 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
3604                                                 struct osd_device *osd)
3605 {
3606         struct osd_thread_info *info = osd_oti_get(env);
3607         struct osd_obj_orphan *oor, *tmp;
3608         struct osd_inode_id id;
3609         struct list_head list;
3610         struct inode *inode;
3611         struct lu_fid fid;
3612         handle_t *jh;
3613         __u32 ino;
3614
3615         INIT_LIST_HEAD(&list);
3616
3617         spin_lock(&osd->od_osfs_lock);
3618         list_for_each_entry_safe(oor, tmp, &osd->od_orphan_list, oor_list) {
3619                 if (oor->oor_env == env) {
3620                         list_del(&oor->oor_list);
3621                         list_add(&oor->oor_list, &list);
3622                 }
3623         }
3624         spin_unlock(&osd->od_osfs_lock);
3625
3626         list_for_each_entry_safe(oor, tmp, &list, oor_list) {
3627
3628                 ino = oor->oor_ino;
3629
3630                 list_del(&oor->oor_list);
3631                 OBD_FREE_PTR(oor);
3632
3633                 osd_id_gen(&id, ino, OSD_OII_NOGEN);
3634                 inode = osd_iget_fid(info, osd, &id, &fid);
3635                 if (IS_ERR(inode))
3636                         continue;
3637
3638                 if (!osd_remote_fid(env, osd, &fid)) {
3639                         iput(inode);
3640                         continue;
3641                 }
3642
3643                 jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC, 1);
3644                 clear_nlink(inode);
3645                 mark_inode_dirty(inode);
3646                 ldiskfs_journal_stop(jh);
3647                 iput(inode);
3648         }
3649
3650         return 0;
3651 }
3652
3653 /**
3654  * OSD layer object create function for OST objects (b=11826).
3655  *
3656  * The FID is inserted into inode xattr here.
3657  *
3658  * \retval   0, on success
3659  * \retval -ve, on error
3660  */
3661 static int osd_create(const struct lu_env *env, struct dt_object *dt,
3662                       struct lu_attr *attr, struct dt_allocation_hint *hint,
3663                       struct dt_object_format *dof, struct thandle *th)
3664 {
3665         const struct lu_fid     *fid    = lu_object_fid(&dt->do_lu);
3666         struct osd_object       *obj    = osd_dt_obj(dt);
3667         struct osd_thread_info  *info   = osd_oti_get(env);
3668         int                      result, on_ost = 0;
3669
3670         ENTRY;
3671
3672         if (dt_object_exists(dt))
3673                 RETURN(-EEXIST);
3674
3675         LINVRNT(osd_invariant(obj));
3676         LASSERT(!dt_object_remote(dt));
3677         LASSERT(osd_is_write_locked(env, obj));
3678         LASSERT(th != NULL);
3679
3680         if (unlikely(fid_is_acct(fid)))
3681                 /* Quota files can't be created from the kernel any more,
3682                  * 'tune2fs -O quota' will take care of creating them */
3683                 RETURN(-EPERM);
3684
3685         result = __osd_create(info, obj, attr, hint, dof, th);
3686         if (result == 0) {
3687                 if (fid_is_idif(fid) &&
3688                     !osd_dev(dt->do_lu.lo_dev)->od_index_in_idif) {
3689                         struct lu_fid *tfid = &info->oti_fid;
3690                         struct ost_id *oi   = &info->oti_ostid;
3691
3692                         fid_to_ostid(fid, oi);
3693                         ostid_to_fid(tfid, oi, 0);
3694                         on_ost = 1;
3695                         result = osd_ea_fid_set(info, obj->oo_inode, tfid,
3696                                                 LMAC_FID_ON_OST, 0);
3697                 } else {
3698                         on_ost = fid_is_on_ost(info, osd_obj2dev(obj),
3699                                                fid, OI_CHECK_FLD);
3700                         result = osd_ea_fid_set(info, obj->oo_inode, fid,
3701                                                 on_ost ? LMAC_FID_ON_OST : 0,
3702                                                 0);
3703                 }
3704                 if (obj->oo_dt.do_body_ops == &osd_body_ops_new)
3705                         obj->oo_dt.do_body_ops = &osd_body_ops;
3706         }
3707
3708         if (!result && !CFS_FAIL_CHECK(OBD_FAIL_OSD_NO_OI_ENTRY))
3709                 result = __osd_oi_insert(env, obj, fid, th);
3710
3711         /* a small optimization - dt_insert() isn't usually applied
3712          * to OST objects, so we don't need to cache OI mapping for
3713          * OST objects */
3714         if (result == 0 && on_ost == 0) {
3715                 struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
3716                 result = osd_idc_find_and_init(env, osd, obj);
3717                 LASSERT(result == 0);
3718         }
3719
3720         LASSERT(ergo(result == 0,
3721                      dt_object_exists(dt) && !dt_object_remote(dt)));
3722         LINVRNT(osd_invariant(obj));
3723         RETURN(result);
3724 }
3725
3726 static int osd_declare_ref_add(const struct lu_env *env, struct dt_object *dt,
3727                                struct thandle *handle)
3728 {
3729         struct osd_thandle *oh;
3730
3731         /* it's possible that object doesn't exist yet */
3732         LASSERT(handle != NULL);
3733
3734         oh = container_of0(handle, struct osd_thandle, ot_super);
3735         LASSERT(oh->ot_handle == NULL);
3736
3737         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
3738                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
3739
3740         osd_idc_find_and_init(env, osd_dev(dt->do_lu.lo_dev), osd_dt_obj(dt));
3741
3742         return 0;
3743 }
3744
3745 /*
3746  * Concurrency: @dt is write locked.
3747  */
3748 static int osd_ref_add(const struct lu_env *env, struct dt_object *dt,
3749                        struct thandle *th)
3750 {
3751         struct osd_object  *obj = osd_dt_obj(dt);
3752         struct inode       *inode = obj->oo_inode;
3753         struct osd_thandle *oh;
3754         int                 rc = 0;
3755
3756         if (!dt_object_exists(dt) || obj->oo_destroyed)
3757                 return -ENOENT;
3758
3759         LINVRNT(osd_invariant(obj));
3760         LASSERT(!dt_object_remote(dt));
3761         LASSERT(osd_is_write_locked(env, obj));
3762         LASSERT(th != NULL);
3763
3764         oh = container_of0(th, struct osd_thandle, ot_super);
3765         LASSERT(oh->ot_handle != NULL);
3766
3767         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
3768
3769         CDEBUG(D_INODE, DFID" increase nlink %d\n",
3770                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
3771         /*
3772          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
3773          * (65000) subdirectories by storing "1" in i_nlink if the link count
3774          * would otherwise overflow. Directory tranversal tools understand
3775          * that (st_nlink == 1) indicates that the filesystem dose not track
3776          * hard links count on the directory, and will not abort subdirectory
3777          * scanning early once (st_nlink - 2) subdirs have been found.
3778          *
3779          * This also has to properly handle the case of inodes with nlink == 0
3780          * in case they are being linked into the PENDING directory
3781          */
3782         spin_lock(&obj->oo_guard);
3783         if (unlikely(inode->i_nlink == 0))
3784                 /* inc_nlink from 0 may cause WARN_ON */
3785                 set_nlink(inode, 1);
3786         else {
3787                 ldiskfs_inc_count(oh->ot_handle, inode);
3788                 if (!S_ISDIR(inode->i_mode))
3789                         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
3790         }
3791         spin_unlock(&obj->oo_guard);
3792
3793         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3794         LINVRNT(osd_invariant(obj));
3795
3796         osd_trans_exec_check(env, th, OSD_OT_REF_ADD);
3797
3798         return rc;
3799 }
3800
3801 static int osd_declare_ref_del(const struct lu_env *env, struct dt_object *dt,
3802                                struct thandle *handle)
3803 {
3804         struct osd_thandle *oh;
3805
3806         if (!dt_object_exists(dt))
3807                 return -ENOENT;
3808
3809         LASSERT(!dt_object_remote(dt));
3810         LASSERT(handle != NULL);
3811
3812         oh = container_of0(handle, struct osd_thandle, ot_super);
3813         LASSERT(oh->ot_handle == NULL);
3814
3815         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
3816                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
3817
3818         return 0;
3819 }
3820
3821 /*
3822  * Concurrency: @dt is write locked.
3823  */
3824 static int osd_ref_del(const struct lu_env *env, struct dt_object *dt,
3825                        struct thandle *th)
3826 {
3827         struct osd_object       *obj = osd_dt_obj(dt);
3828         struct inode            *inode = obj->oo_inode;
3829         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
3830         struct osd_thandle      *oh;
3831
3832         if (!dt_object_exists(dt))
3833                 return -ENOENT;
3834
3835         LINVRNT(osd_invariant(obj));
3836         LASSERT(!dt_object_remote(dt));
3837         LASSERT(osd_is_write_locked(env, obj));
3838         LASSERT(th != NULL);
3839
3840         oh = container_of0(th, struct osd_thandle, ot_super);
3841         LASSERT(oh->ot_handle != NULL);
3842
3843         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
3844
3845         spin_lock(&obj->oo_guard);
3846         /* That can be result of upgrade from old Lustre version and
3847          * applied only to local files.  Just skip this ref_del call.
3848          * ext4_unlink() only treats this as a warning, don't LASSERT here.*/
3849         if (inode->i_nlink == 0) {
3850                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
3851                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
3852                              ", maybe an upgraded file? (LU-3915)\n",
3853                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
3854                 spin_unlock(&obj->oo_guard);
3855                 return 0;
3856         }
3857
3858         CDEBUG(D_INODE, DFID" decrease nlink %d\n",
3859                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
3860
3861         ldiskfs_dec_count(oh->ot_handle, inode);
3862         spin_unlock(&obj->oo_guard);
3863
3864         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3865         LINVRNT(osd_invariant(obj));
3866
3867         osd_trans_exec_check(env, th, OSD_OT_REF_DEL);
3868
3869         return 0;
3870 }
3871
3872 /*
3873  * Concurrency: @dt is read locked.
3874  */
3875 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
3876                          struct lu_buf *buf, const char *name)
3877 {
3878         struct osd_object      *obj    = osd_dt_obj(dt);
3879         struct inode           *inode  = obj->oo_inode;
3880         struct osd_thread_info *info   = osd_oti_get(env);
3881         struct dentry          *dentry = &info->oti_obj_dentry;
3882         bool                    cache_xattr = false;
3883         int                     rc;
3884
3885         LASSERT(buf);
3886
3887         /* version get is not real XATTR but uses xattr API */
3888         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
3889                 dt_obj_version_t *ver = buf->lb_buf;
3890
3891                 /* for version we are just using xattr API but change inode
3892                  * field instead */
3893                 if (buf->lb_len == 0)
3894                         return sizeof(dt_obj_version_t);
3895
3896                 if (buf->lb_len < sizeof(dt_obj_version_t))
3897                         return -ERANGE;
3898
3899                 CDEBUG(D_INODE, "Get version %#llx for inode %lu\n",
3900                        LDISKFS_I(inode)->i_fs_version, inode->i_ino);
3901
3902                 *ver = LDISKFS_I(inode)->i_fs_version;
3903
3904                 return sizeof(dt_obj_version_t);
3905         }
3906
3907         if (!dt_object_exists(dt))
3908                 return -ENOENT;
3909
3910         LASSERT(!dt_object_remote(dt));
3911         LASSERT(inode->i_op != NULL);
3912         LASSERT(inode->i_op->getxattr != NULL);
3913
3914         if (strcmp(name, XATTR_NAME_LOV) == 0 ||
3915             strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
3916                 cache_xattr = true;
3917
3918         if (cache_xattr) {
3919                 rc = osd_oxc_get(obj, name, buf);
3920                 if (rc != -ENOENT)
3921                         return rc;
3922         }
3923
3924         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
3925                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
3926                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
3927                 struct filter_fid *ff;
3928                 struct ost_layout *ol;
3929
3930                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
3931                 if (rc)
3932                         return rc;
3933
3934                 LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
3935
3936                 rc = sizeof(*ff);
3937                 if (buf->lb_len == 0 || !buf->lb_buf)
3938                         return rc;
3939
3940                 if (buf->lb_len < rc)
3941                         return -ERANGE;
3942
3943                 ff = buf->lb_buf;
3944                 ol = &ff->ff_layout;
3945                 ol->ol_stripe_count = cpu_to_le32(loa->loa_parent_fid.f_ver >>
3946                                                   PFID_STRIPE_IDX_BITS);
3947                 ol->ol_stripe_size = cpu_to_le32(loa->loa_stripe_size);
3948                 loa->loa_parent_fid.f_ver &= PFID_STRIPE_COUNT_MASK;
3949                 fid_cpu_to_le(&ff->ff_parent, &loa->loa_parent_fid);
3950                 if (lma->lma_compat & LMAC_COMP_INFO) {
3951                         ol->ol_comp_start = cpu_to_le64(loa->loa_comp_start);
3952                         ol->ol_comp_end = cpu_to_le64(loa->loa_comp_end);
3953                         ol->ol_comp_id = cpu_to_le32(loa->loa_comp_id);
3954                 } else {
3955                         ol->ol_comp_start = 0;
3956                         ol->ol_comp_end = 0;
3957                         ol->ol_comp_id = 0;
3958                 }
3959         } else {
3960                 rc = __osd_xattr_get(inode, dentry, name,
3961                                      buf->lb_buf, buf->lb_len);
3962         }
3963
3964         if (cache_xattr) {
3965                 if (rc == -ENOENT || rc == -ENODATA)
3966                         osd_oxc_add(obj, name, NULL, 0);
3967                 else if (rc > 0 && buf->lb_buf != NULL)
3968                         osd_oxc_add(obj, name, buf->lb_buf, rc);
3969         }
3970
3971         return rc;
3972 }
3973
3974 static int osd_declare_xattr_set(const struct lu_env *env,
3975                                  struct dt_object *dt,
3976                                  const struct lu_buf *buf, const char *name,
3977                                  int fl, struct thandle *handle)
3978 {
3979         struct osd_thandle *oh;
3980         int credits = 0;
3981         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3982
3983         LASSERT(handle != NULL);
3984
3985         oh = container_of0(handle, struct osd_thandle, ot_super);
3986         LASSERT(oh->ot_handle == NULL);
3987
3988         if (strcmp(name, XATTR_NAME_LMA) == 0) {
3989                 /* For non-upgrading case, the LMA is set first and
3990                  * usually fit inode. But for upgrade case, the LMA
3991                  * may be in another separated EA block. */
3992                 if (dt_object_exists(dt)) {
3993                         if (fl == LU_XATTR_REPLACE)
3994                                 credits = 1;
3995                         else
3996                                 goto upgrade;
3997                 }
3998         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
3999                 credits = 1;
4000         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
4001                 /* We may need to delete the old PFID EA. */
4002                 credits = LDISKFS_MAXQUOTAS_DEL_BLOCKS(sb);
4003                 if (fl == LU_XATTR_REPLACE)
4004                         credits += 1;
4005                 else
4006                         goto upgrade;
4007         } else {
4008                 /* If some name entry resides on remote MDT, then will create
4009                  * agent entry under remote parent. On the other hand, if the
4010                  * remote entry will be removed, then related agent entry may
4011                  * need to be removed from the remote parent. So there may be
4012                  * kinds of cases, let's declare enough credits. The credits
4013                  * for create agent entry is enough for remove case. */
4014                 if (strcmp(name, XATTR_NAME_LINK) == 0) {
4015                         credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
4016                         if (dt_object_exists(dt))
4017                                 credits += 1; /* For updating LMA */
4018                 }
4019
4020 upgrade:
4021                 credits += osd_dto_credits_noquota[DTO_XATTR_SET];
4022
4023                 if (buf != NULL) {
4024                         ssize_t buflen;
4025
4026                         if (buf->lb_buf == NULL && dt_object_exists(dt)) {
4027                                 /* learn xattr size from osd_xattr_get if
4028                                    attribute has not been read yet */
4029                                 buflen = __osd_xattr_get(
4030                                     osd_dt_obj(dt)->oo_inode,
4031                                     &osd_oti_get(env)->oti_obj_dentry,
4032                                     name, NULL, 0);
4033                                 if (buflen < 0)
4034                                         buflen = 0;
4035                         } else {
4036                                 buflen = buf->lb_len;
4037                         }
4038
4039                         if (buflen > sb->s_blocksize) {
4040                                 credits += osd_calc_bkmap_credits(
4041                                     sb, NULL, 0, -1,
4042                                     (buflen + sb->s_blocksize - 1) >>
4043                                     sb->s_blocksize_bits);
4044                         }
4045                 }
4046                 /*
4047                  * xattr set may involve inode quota change, reserve credits for
4048                  * dquot_initialize()
4049                  */
4050                 credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4051         }
4052
4053         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
4054
4055         return 0;
4056 }
4057
4058 static int osd_xattr_set_pfid(const struct lu_env *env, struct osd_object *obj,
4059                               const struct lu_buf *buf, int fl,
4060                               struct thandle *handle)
4061 {
4062         struct osd_thread_info *info = osd_oti_get(env);
4063         struct dentry *dentry = &info->oti_obj_dentry;
4064         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4065         struct lustre_mdt_attrs *lma = &loa->loa_lma;
4066         struct inode *inode = obj->oo_inode;
4067         struct filter_fid *ff = buf->lb_buf;
4068         struct ost_layout *ol = &ff->ff_layout;
4069         int flags = XATTR_REPLACE;
4070         int rc;
4071         ENTRY;
4072
4073         if (buf->lb_len != sizeof(*ff) && buf->lb_len != sizeof(struct lu_fid))
4074                 RETURN(-EINVAL);
4075
4076         rc = osd_get_lma(info, inode, dentry, loa);
4077         if (rc == -ENODATA) {
4078                 /* Usually for upgarding from old device */
4079                 lustre_loa_init(loa, lu_object_fid(&obj->oo_dt.do_lu),
4080                                 LMAC_FID_ON_OST, 0);
4081                 flags = XATTR_CREATE;
4082         } else if (rc) {
4083                 RETURN(rc);
4084         }
4085
4086         if (!rc && lma->lma_compat & LMAC_STRIPE_INFO) {
4087                 if ((fl & LU_XATTR_CREATE) && !(fl & LU_XATTR_REPLACE))
4088                         RETURN(-EEXIST);
4089
4090                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256) {
4091                         /* Separate PFID EA from LMA */
4092                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4093                         lustre_lma_swab(lma);
4094                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4095                                              sizeof(*lma), XATTR_REPLACE);
4096                         if (!rc) {
4097                                 obj->oo_pfid_in_lma = 0;
4098                                 rc = LU_XATTR_CREATE;
4099                         }
4100
4101                         RETURN(rc);
4102                 }
4103         } else {
4104                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256)
4105                         RETURN(fl);
4106
4107                 /* Old client does not send stripe information,
4108                  * then store the PFID EA on disk separatedly. */
4109                 if (unlikely(buf->lb_len == sizeof(struct lu_fid) ||
4110                              ol->ol_stripe_size == 0))
4111                         RETURN(fl);
4112
4113                 /* Remove old PFID EA entry firstly. */
4114                 ll_vfs_dq_init(inode);
4115                 rc = inode->i_op->removexattr(dentry, XATTR_NAME_FID);
4116                 if (rc == -ENODATA) {
4117                         if ((fl & LU_XATTR_REPLACE) && !(fl & LU_XATTR_CREATE))
4118                                 RETURN(rc);
4119                 } else if (rc) {
4120                         RETURN(rc);
4121                 }
4122         }
4123
4124         fid_le_to_cpu(&loa->loa_parent_fid, &ff->ff_parent);
4125         if (likely(ol->ol_stripe_size != 0)) {
4126                 loa->loa_parent_fid.f_ver |= le32_to_cpu(ol->ol_stripe_count) <<
4127                                              PFID_STRIPE_IDX_BITS;
4128                 loa->loa_stripe_size = le32_to_cpu(ol->ol_stripe_size);
4129                 lma->lma_compat |= LMAC_STRIPE_INFO;
4130                 if (ol->ol_comp_id != 0) {
4131                         loa->loa_comp_id = le32_to_cpu(ol->ol_comp_id);
4132                         loa->loa_comp_start = le64_to_cpu(ol->ol_comp_start);
4133                         loa->loa_comp_end = le64_to_cpu(ol->ol_comp_end);
4134                         lma->lma_compat |= LMAC_COMP_INFO;
4135                 }
4136         }
4137
4138         lustre_loa_swab(loa, false);
4139
4140         /* Store the PFID EA inside LMA. */
4141         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa, sizeof(*loa),
4142                              flags);
4143         if (!rc)
4144                 obj->oo_pfid_in_lma = 1;
4145
4146         RETURN(rc);
4147 }
4148
4149 /*
4150  * In DNE environment, the object (in spite of regular file or directory)
4151  * and its name entry may reside on different MDTs. Under such case, we will
4152  * create an agent entry on the MDT where the object resides. The agent entry
4153  * references the object locally, that makes the object to be visible to the
4154  * userspace when mounted as 'ldiskfs' directly. Then the userspace tools,
4155  * such as 'tar' can handle the object properly.
4156  *
4157  * We handle the agent entry during set linkEA that is the common interface
4158  * for both regular file and directroy, can handle kinds of cases, such as
4159  * create/link/unlink/rename, and so on.
4160  *
4161  * NOTE: we can NOT do that when ea_{insert,delete} that is only for directory.
4162  *
4163  * XXX: There are two known issues:
4164  * 1. For one object, we will create at most one agent entry even if there
4165  *    may be more than one cross-MDTs hard links on the object. So the local
4166  *    e2fsck may claim that the object's nlink is larger than the name entries
4167  *    that reference such inode. And in further, the e2fsck will fix the nlink
4168  *    attribute to match the local references. Then it will cause the object's
4169  *    nlink attribute to be inconsistent with the global references. it is bad
4170  *    but not fatal. The ref_del() can handle the zero-referenced case. On the
4171  *    other hand, the global namespace LFSCK can repair the object's attribute
4172  *    according to the linkEA.
4173  * 2. There may be too many hard links on the object as to its linkEA overflow,
4174  *    then the linkEA entry for cross-MDTs reference may be discarded. If such
4175  *    case happened, then at this point, we do not know whether there are some
4176  *    cross-MDTs reference. But there are local references, it guarantees that
4177  *    object is visible to userspace when mounted as 'ldiskfs'. That is enough.
4178  */
4179 static int osd_xattr_handle_linkea(const struct lu_env *env,
4180                                    struct osd_device *osd,
4181                                    struct osd_object *obj,
4182                                    const struct lu_buf *buf,
4183                                    struct thandle *handle)
4184 {
4185         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
4186         struct lu_fid *tfid = &osd_oti_get(env)->oti_fid3;
4187         struct linkea_data ldata = { .ld_buf = (struct lu_buf *)buf };
4188         struct lu_name tmpname;
4189         struct osd_thandle *oh;
4190         int rc;
4191         bool remote = false;
4192         ENTRY;
4193
4194         oh = container_of0(handle, struct osd_thandle, ot_super);
4195         LASSERT(oh->ot_handle != NULL);
4196
4197         rc = linkea_init_with_rec(&ldata);
4198         if (!rc) {
4199                 linkea_first_entry(&ldata);
4200                 while (ldata.ld_lee != NULL && !remote) {
4201                         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen,
4202                                             &tmpname, tfid);
4203                         if (osd_remote_fid(env, osd, tfid) > 0)
4204                                 remote = true;
4205                         else
4206                                 linkea_next_entry(&ldata);
4207                 }
4208         } else if (rc == -ENODATA) {
4209                 rc = 0;
4210         } else {
4211                 RETURN(rc);
4212         }
4213
4214         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu) && !remote) {
4215                 rc = osd_delete_from_remote_parent(env, osd, obj, oh, false);
4216                 if (rc)
4217                         CERROR("%s: failed to remove agent entry for "DFID
4218                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4219         } else if (!lu_object_has_agent_entry(&obj->oo_dt.do_lu) && remote) {
4220                 rc = osd_add_to_remote_parent(env, osd, obj, oh);
4221                 if (rc)
4222                         CERROR("%s: failed to create agent entry for "DFID
4223                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4224         }
4225
4226         RETURN(rc);
4227 }
4228
4229 /*
4230  * Concurrency: @dt is write locked.
4231  */
4232 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
4233                          const struct lu_buf *buf, const char *name, int fl,
4234                          struct thandle *handle)
4235 {
4236         struct osd_object *obj = osd_dt_obj(dt);
4237         struct osd_device *osd = osd_obj2dev(obj);
4238         struct inode *inode = obj->oo_inode;
4239         struct osd_thread_info *info = osd_oti_get(env);
4240         int fs_flags = 0;
4241         int len;
4242         int rc;
4243         ENTRY;
4244
4245         LASSERT(handle);
4246         LASSERT(buf);
4247
4248         /* version set is not real XATTR */
4249         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4250                 dt_obj_version_t *version = buf->lb_buf;
4251
4252                 /* for version we are just using xattr API but change inode
4253                  * field instead */
4254                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
4255
4256                 CDEBUG(D_INODE, "Set version %#llx (old %#llx) for inode %lu\n",
4257                        *version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4258
4259                 LDISKFS_I(inode)->i_fs_version = *version;
4260                 /* Version is set after all inode operations are finished,
4261                  * so we should mark it dirty here */
4262                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
4263
4264                 RETURN(0);
4265         }
4266
4267         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zu\n",
4268                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
4269
4270         len = buf->lb_len;
4271         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4272
4273         /* For the OST device with 256 bytes inode size by default,
4274          * the PFID EA will be stored together with LMA EA to avoid
4275          * performance trouble. Otherwise the PFID EA can be stored
4276          * independently. LU-8998 */
4277         if (strcmp(name, XATTR_NAME_FID) == 0 && osd->od_is_ost &&
4278             (LDISKFS_INODE_SIZE(inode->i_sb) <= 256 || obj->oo_pfid_in_lma)) {
4279                 LASSERT(buf->lb_buf);
4280
4281                 fl = osd_xattr_set_pfid(env, obj, buf, fl, handle);
4282                 if (fl <= 0)
4283                         RETURN(fl);
4284         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
4285                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4286                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4287
4288                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4289                 if (rc)
4290                         RETURN(rc);
4291
4292                 lma->lma_incompat |= LMAI_STRIPED;
4293                 lustre_lma_swab(lma);
4294                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4295                                      sizeof(*lma), XATTR_REPLACE);
4296                 if (rc != 0)
4297                         RETURN(rc);
4298         } else if (strcmp(name, XATTR_NAME_LINK) == 0) {
4299                 LASSERT(!osd->od_is_ost);
4300
4301                 rc = osd_xattr_handle_linkea(env, osd, obj, buf, handle);
4302                 if (rc)
4303                         RETURN(rc);
4304         }
4305
4306         if (fl & LU_XATTR_REPLACE)
4307                 fs_flags |= XATTR_REPLACE;
4308
4309         if (fl & LU_XATTR_CREATE)
4310                 fs_flags |= XATTR_CREATE;
4311
4312         rc = __osd_xattr_set(info, inode, name, buf->lb_buf, len, fs_flags);
4313         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4314
4315         if (rc == 0 &&
4316             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4317              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4318                 osd_oxc_add(obj, name, buf->lb_buf, buf->lb_len);
4319
4320         return rc;
4321 }
4322
4323 /*
4324  * Concurrency: @dt is read locked.
4325  */
4326 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
4327                           const struct lu_buf *buf)
4328 {
4329         struct osd_object      *obj    = osd_dt_obj(dt);
4330         struct inode           *inode  = obj->oo_inode;
4331         struct osd_thread_info *info   = osd_oti_get(env);
4332         struct dentry          *dentry = &info->oti_obj_dentry;
4333
4334         if (!dt_object_exists(dt))
4335                 return -ENOENT;
4336
4337         LASSERT(!dt_object_remote(dt));
4338         LASSERT(inode->i_op != NULL);
4339         LASSERT(inode->i_op->listxattr != NULL);
4340
4341         dentry->d_inode = inode;
4342         dentry->d_sb = inode->i_sb;
4343         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
4344 }
4345
4346 static int osd_declare_xattr_del(const struct lu_env *env,
4347                                  struct dt_object *dt, const char *name,
4348                                  struct thandle *handle)
4349 {
4350         struct osd_thandle *oh;
4351         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4352
4353         LASSERT(!dt_object_remote(dt));
4354         LASSERT(handle != NULL);
4355
4356         oh = container_of0(handle, struct osd_thandle, ot_super);
4357         LASSERT(oh->ot_handle == NULL);
4358
4359         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
4360                              osd_dto_credits_noquota[DTO_XATTR_SET]);
4361         /*
4362          * xattr del may involve inode quota change, reserve credits for
4363          * dquot_initialize()
4364          */
4365         oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4366
4367         return 0;
4368 }
4369
4370 /*
4371  * Concurrency: @dt is write locked.
4372  */
4373 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
4374                          const char *name, struct thandle *handle)
4375 {
4376         struct osd_object      *obj    = osd_dt_obj(dt);
4377         struct inode           *inode  = obj->oo_inode;
4378         struct osd_thread_info *info   = osd_oti_get(env);
4379         struct dentry          *dentry = &info->oti_obj_dentry;
4380         int                     rc;
4381
4382         if (!dt_object_exists(dt))
4383                 return -ENOENT;
4384
4385         LASSERT(!dt_object_remote(dt));
4386         LASSERT(inode->i_op != NULL);
4387         LASSERT(inode->i_op->removexattr != NULL);
4388         LASSERT(handle != NULL);
4389
4390         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4391
4392         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4393                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
4394
4395                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
4396                                  &info->oti_ost_attrs);
4397                 if (!rc) {
4398                         LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4399
4400                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4401                         lustre_lma_swab(lma);
4402                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4403                                              sizeof(*lma), XATTR_REPLACE);
4404                         if (!rc)
4405                                 obj->oo_pfid_in_lma = 0;
4406                 }
4407         } else {
4408                 ll_vfs_dq_init(inode);
4409                 dentry->d_inode = inode;
4410                 dentry->d_sb = inode->i_sb;
4411                 rc = inode->i_op->removexattr(dentry, name);
4412         }
4413
4414         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4415
4416         if (rc == 0 &&
4417             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4418              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4419                 osd_oxc_del(obj, name);
4420
4421         return rc;
4422 }
4423
4424 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt,
4425                            __u64 start, __u64 end)
4426 {
4427         struct osd_object       *obj    = osd_dt_obj(dt);
4428         struct inode            *inode  = obj->oo_inode;
4429         struct osd_thread_info  *info   = osd_oti_get(env);
4430         struct dentry           *dentry = &info->oti_obj_dentry;
4431         struct file             *file   = &info->oti_file;
4432         int                     rc;
4433
4434         ENTRY;
4435
4436         dentry->d_inode = inode;
4437         dentry->d_sb = inode->i_sb;
4438         file->f_path.dentry = dentry;
4439         file->f_mapping = inode->i_mapping;
4440         file->f_op = inode->i_fop;
4441         set_file_inode(file, inode);
4442
4443         rc = ll_vfs_fsync_range(file, start, end, 0);
4444
4445         RETURN(rc);
4446 }
4447
4448 static int osd_invalidate(const struct lu_env *env, struct dt_object *dt)
4449 {
4450         return 0;
4451 }
4452
4453 /*
4454  * Index operations.
4455  */
4456
4457 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
4458                            const struct dt_index_features *feat)
4459 {
4460         struct iam_descr *descr;
4461
4462         if (osd_object_is_root(o))
4463                 return feat == &dt_directory_features;
4464
4465         LASSERT(o->oo_dir != NULL);
4466
4467         descr = o->oo_dir->od_container.ic_descr;
4468         if (feat == &dt_directory_features) {
4469                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
4470                         return 1;
4471                 else
4472                         return 0;
4473         } else {
4474                 return
4475                         feat->dif_keysize_min <= descr->id_key_size &&
4476                         descr->id_key_size <= feat->dif_keysize_max &&
4477                         feat->dif_recsize_min <= descr->id_rec_size &&
4478                         descr->id_rec_size <= feat->dif_recsize_max &&
4479                         !(feat->dif_flags & (DT_IND_VARKEY |
4480                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
4481                         ergo(feat->dif_flags & DT_IND_UPDATE,
4482                              1 /* XXX check that object (and file system) is
4483                                 * writable */);
4484         }
4485 }
4486
4487 static int osd_iam_container_init(const struct lu_env *env,
4488                                   struct osd_object *obj,
4489                                   struct osd_directory *dir)
4490 {
4491         struct iam_container *bag = &dir->od_container;
4492         int result;
4493
4494         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
4495         if (result != 0)
4496                 return result;
4497
4498         result = iam_container_setup(bag);
4499         if (result == 0)
4500                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
4501         else
4502                 iam_container_fini(bag);
4503
4504         return result;
4505 }
4506
4507
4508 /*
4509  * Concurrency: no external locking is necessary.
4510  */
4511 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
4512                          const struct dt_index_features *feat)
4513 {
4514         int                      result;
4515         int                      skip_iam = 0;
4516         struct osd_object       *obj = osd_dt_obj(dt);
4517
4518         LINVRNT(osd_invariant(obj));
4519
4520         if (osd_object_is_root(obj)) {
4521                 dt->do_index_ops = &osd_index_ea_ops;
4522                 result = 0;
4523         } else if (feat == &dt_directory_features) {
4524                 dt->do_index_ops = &osd_index_ea_ops;
4525                 if (obj->oo_inode == NULL || S_ISDIR(obj->oo_inode->i_mode))
4526                         result = 0;
4527                 else
4528                         result = -ENOTDIR;
4529                 skip_iam = 1;
4530         } else if (unlikely(feat == &dt_otable_features)) {
4531                 dt->do_index_ops = &osd_otable_ops;
4532                 return 0;
4533         } else if (unlikely(feat == &dt_acct_features)) {
4534                 dt->do_index_ops = &osd_acct_index_ops;
4535                 result = 0;
4536                 skip_iam = 1;
4537         } else if (!osd_has_index(obj)) {
4538                 struct osd_directory *dir;
4539                 struct osd_device *osd = osd_obj2dev(obj);
4540                 const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4541
4542                 OBD_ALLOC_PTR(dir);
4543                 if (dir) {
4544
4545                         spin_lock(&obj->oo_guard);
4546                         if (obj->oo_dir == NULL)
4547                                 obj->oo_dir = dir;
4548                         else
4549                                 /*
4550                                  * Concurrent thread allocated container data.
4551                                  */
4552                                 OBD_FREE_PTR(dir);
4553                         spin_unlock(&obj->oo_guard);
4554                         /*
4555                          * Now, that we have container data, serialize its
4556                          * initialization.
4557                          */
4558                         down_write(&obj->oo_ext_idx_sem);
4559                         /*
4560                          * recheck under lock.
4561                          */
4562
4563                         if (osd_has_index(obj)) {
4564                                 result = 0;
4565                                 goto unlock;
4566                         }
4567
4568                         result = osd_iam_container_init(env, obj, obj->oo_dir);
4569                         if (result || feat == &dt_lfsck_namespace_features ||
4570                             feat == &dt_lfsck_layout_orphan_features ||
4571                             feat == &dt_lfsck_layout_dangling_features)
4572                                 goto unlock;
4573
4574                         result = osd_index_register(osd, fid,
4575                                                     feat->dif_keysize_max,
4576                                                     feat->dif_recsize_max);
4577                         if (result < 0)
4578                                 CWARN("%s: failed to register index "
4579                                       DFID": rc = %d\n",
4580                                       osd_name(osd), PFID(fid), result);
4581                         else if (result > 0)
4582                                 result = 0;
4583                         else
4584                                 CDEBUG(D_LFSCK, "%s: index object "DFID
4585                                        " (%d/%d) registered\n",
4586                                        osd_name(osd), PFID(fid),
4587                                        (int)feat->dif_keysize_max,
4588                                        (int)feat->dif_recsize_max);
4589
4590 unlock:
4591                         up_write(&obj->oo_ext_idx_sem);
4592                 } else {
4593                         result = -ENOMEM;
4594                 }
4595         } else {
4596                 result = 0;
4597         }
4598
4599         if (result == 0 && skip_iam == 0) {
4600                 if (!osd_iam_index_probe(env, obj, feat))
4601                         result = -ENOTDIR;
4602         }
4603         LINVRNT(osd_invariant(obj));
4604
4605         return result;
4606 }
4607
4608 static int osd_otable_it_attr_get(const struct lu_env *env,
4609                                  struct dt_object *dt,
4610                                  struct lu_attr *attr)
4611 {
4612         attr->la_valid = 0;
4613         return 0;
4614 }
4615
4616 static const struct dt_object_operations osd_obj_ops = {
4617         .do_read_lock           = osd_read_lock,
4618         .do_write_lock          = osd_write_lock,
4619         .do_read_unlock         = osd_read_unlock,
4620         .do_write_unlock        = osd_write_unlock,
4621         .do_write_locked        = osd_write_locked,
4622         .do_attr_get            = osd_attr_get,
4623         .do_declare_attr_set    = osd_declare_attr_set,
4624         .do_attr_set            = osd_attr_set,
4625         .do_ah_init             = osd_ah_init,
4626         .do_declare_create      = osd_declare_create,
4627         .do_create              = osd_create,
4628         .do_declare_destroy     = osd_declare_destroy,
4629         .do_destroy             = osd_destroy,
4630         .do_index_try           = osd_index_try,
4631         .do_declare_ref_add     = osd_declare_ref_add,
4632         .do_ref_add             = osd_ref_add,
4633         .do_declare_ref_del     = osd_declare_ref_del,
4634         .do_ref_del             = osd_ref_del,
4635         .do_xattr_get           = osd_xattr_get,
4636         .do_declare_xattr_set   = osd_declare_xattr_set,
4637         .do_xattr_set           = osd_xattr_set,
4638         .do_declare_xattr_del   = osd_declare_xattr_del,
4639         .do_xattr_del           = osd_xattr_del,
4640         .do_xattr_list          = osd_xattr_list,
4641         .do_object_sync         = osd_object_sync,
4642         .do_invalidate          = osd_invalidate,
4643 };
4644
4645 static const struct dt_object_operations osd_obj_otable_it_ops = {
4646         .do_attr_get    = osd_otable_it_attr_get,
4647         .do_index_try   = osd_index_try,
4648 };
4649
4650 static int osd_index_declare_iam_delete(const struct lu_env *env,
4651                                         struct dt_object *dt,
4652                                         const struct dt_key *key,
4653                                         struct thandle *handle)
4654 {
4655         struct osd_thandle    *oh;
4656
4657         oh = container_of0(handle, struct osd_thandle, ot_super);
4658         LASSERT(oh->ot_handle == NULL);
4659
4660         /* Recycle  may cause additional three blocks to be changed. */
4661         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
4662                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
4663
4664         return 0;
4665 }
4666
4667 /**
4668  *      delete a (key, value) pair from index \a dt specified by \a key
4669  *
4670  *      \param  dt      osd index object
4671  *      \param  key     key for index
4672  *      \param  rec     record reference
4673  *      \param  handle  transaction handler
4674  *
4675  *      \retval  0  success
4676  *      \retval -ve   failure
4677  */
4678 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
4679                                 const struct dt_key *key,
4680                                 struct thandle *handle)
4681 {
4682         struct osd_thread_info *oti = osd_oti_get(env);
4683         struct osd_object      *obj = osd_dt_obj(dt);
4684         struct osd_thandle     *oh;
4685         struct iam_path_descr  *ipd;
4686         struct iam_container   *bag = &obj->oo_dir->od_container;
4687         int                     rc;
4688         ENTRY;
4689
4690         if (!dt_object_exists(dt))
4691                 RETURN(-ENOENT);
4692
4693         LINVRNT(osd_invariant(obj));
4694         LASSERT(!dt_object_remote(dt));
4695         LASSERT(bag->ic_object == obj->oo_inode);
4696         LASSERT(handle != NULL);
4697
4698         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
4699
4700         ipd = osd_idx_ipd_get(env, bag);
4701         if (unlikely(ipd == NULL))
4702                 RETURN(-ENOMEM);
4703
4704         oh = container_of0(handle, struct osd_thandle, ot_super);
4705         LASSERT(oh->ot_handle != NULL);
4706         LASSERT(oh->ot_handle->h_transaction != NULL);
4707
4708         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
4709                 /* swab quota uid/gid provided by caller */
4710                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4711                 key = (const struct dt_key *)&oti->oti_quota_id;
4712         }
4713
4714         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
4715         osd_ipd_put(env, bag, ipd);
4716         LINVRNT(osd_invariant(obj));
4717         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
4718         RETURN(rc);
4719 }
4720
4721 static int osd_index_declare_ea_delete(const struct lu_env *env,
4722                                        struct dt_object *dt,
4723                                        const struct dt_key *key,
4724                                        struct thandle *handle)
4725 {
4726         struct osd_thandle *oh;
4727         struct inode       *inode;
4728         int                 rc, credits;
4729         ENTRY;
4730
4731         LASSERT(!dt_object_remote(dt));
4732         LASSERT(handle != NULL);
4733
4734         oh = container_of0(handle, struct osd_thandle, ot_super);
4735         LASSERT(oh->ot_handle == NULL);
4736
4737         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE];
4738         osd_trans_declare_op(env, oh, OSD_OT_DELETE, credits);
4739
4740         inode = osd_dt_obj(dt)->oo_inode;
4741         if (inode == NULL)
4742                 RETURN(-ENOENT);
4743
4744         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
4745                                    i_projid_read(inode), 0, oh, osd_dt_obj(dt),
4746                                    NULL, OSD_QID_BLK);
4747         RETURN(rc);
4748 }
4749
4750 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
4751                                           struct dt_rec *fid)
4752 {
4753         struct osd_fid_pack *rec;
4754         int                  rc = -ENODATA;
4755
4756         if (de->file_type & LDISKFS_DIRENT_LUFID) {
4757                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
4758                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
4759                 if (rc == 0 && unlikely(!fid_is_sane((struct lu_fid *)fid)))
4760                         rc = -EINVAL;
4761         }
4762         return rc;
4763 }
4764
4765 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
4766                           const struct lu_fid *fid)
4767 {
4768         struct seq_server_site  *ss = osd_seq_site(osd);
4769         ENTRY;
4770
4771         /* FID seqs not in FLDB, must be local seq */
4772         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
4773                 RETURN(0);
4774
4775         /* If FLD is not being initialized yet, it only happens during the
4776          * initialization, likely during mgs initialization, and we assume
4777          * this is local FID. */
4778         if (ss == NULL || ss->ss_server_fld == NULL)
4779                 RETURN(0);
4780
4781         /* Only check the local FLDB here */
4782         if (osd_seq_exists(env, osd, fid_seq(fid)))
4783                 RETURN(0);
4784
4785         RETURN(1);
4786 }
4787
4788 static void osd_take_care_of_agent(const struct lu_env *env,
4789                                    struct osd_device *osd,
4790                                    struct osd_thandle *oh,
4791                                    struct ldiskfs_dir_entry_2 *de)
4792 {
4793         struct lu_fid *fid = &osd_oti_get(env)->oti_fid;
4794         struct osd_idmap_cache *idc;
4795         int rc, schedule = 0;
4796
4797         LASSERT(de != NULL);
4798
4799         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
4800         if (likely(rc == 0)) {
4801                 idc = osd_idc_find_or_init(env, osd, fid);
4802                 if (IS_ERR(idc) || idc->oic_remote)
4803                         schedule = 1;
4804         } else if (rc == -ENODATA) {
4805                 /* can't get FID, postpone to the end of the
4806                  * transaction when iget() is safe */
4807                 schedule = 1;
4808         } else {
4809                 CERROR("%s: can't get FID: rc = %d\n", osd_name(osd), rc);
4810         }
4811         if (schedule)
4812                 osd_schedule_agent_inode_removal(env, oh,
4813                                                  le32_to_cpu(de->inode));
4814 }
4815
4816 /**
4817  * Index delete function for interoperability mode (b11826).
4818  * It will remove the directory entry added by osd_index_ea_insert().
4819  * This entry is needed to maintain name->fid mapping.
4820  *
4821  * \param key,  key i.e. file entry to be deleted
4822  *
4823  * \retval   0, on success
4824  * \retval -ve, on error
4825  */
4826 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
4827                                const struct dt_key *key, struct thandle *handle)
4828 {
4829         struct osd_object          *obj = osd_dt_obj(dt);
4830         struct inode               *dir = obj->oo_inode;
4831         struct dentry              *dentry;
4832         struct osd_thandle         *oh;
4833         struct ldiskfs_dir_entry_2 *de = NULL;
4834         struct buffer_head         *bh;
4835         struct htree_lock          *hlock = NULL;
4836         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
4837         int                        rc;
4838         ENTRY;
4839
4840         if (!dt_object_exists(dt))
4841                 RETURN(-ENOENT);
4842
4843         LINVRNT(osd_invariant(obj));
4844         LASSERT(!dt_object_remote(dt));
4845         LASSERT(handle != NULL);
4846
4847         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
4848
4849         oh = container_of(handle, struct osd_thandle, ot_super);
4850         LASSERT(oh->ot_handle != NULL);
4851         LASSERT(oh->ot_handle->h_transaction != NULL);
4852
4853         ll_vfs_dq_init(dir);
4854         dentry = osd_child_dentry_get(env, obj,
4855                                       (char *)key, strlen((char *)key));
4856
4857         if (obj->oo_hl_head != NULL) {
4858                 hlock = osd_oti_get(env)->oti_hlock;
4859                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4860                                    dir, LDISKFS_HLOCK_DEL);
4861         } else {
4862                 down_write(&obj->oo_ext_idx_sem);
4863         }
4864
4865         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
4866         if (!IS_ERR(bh)) {
4867                 /* If this is not the ".." entry, it might be a remote DNE
4868                  * entry and  we need to check if the FID is for a remote
4869                  * MDT.  If the FID is  not in the directory entry (e.g.
4870                  * upgraded 1.8 filesystem without dirdata enabled) then
4871                  * we need to get the FID from the LMA. For a remote directory
4872                  * there HAS to be an LMA, it cannot be an IGIF inode in this
4873                  * case.
4874                  *
4875                  * Delete the entry before the agent inode in order to
4876                  * simplify error handling.  At worst an error after deleting
4877                  * the entry first might leak the agent inode afterward. The
4878                  * reverse would need filesystem abort in case of error deleting
4879                  * the entry after the agent had been removed, or leave a
4880                  * dangling entry pointing at a random inode. */
4881                 if (strcmp((char *)key, dotdot) != 0)
4882                         osd_take_care_of_agent(env, osd, oh, de);
4883                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
4884                 brelse(bh);
4885         } else {
4886                 rc = PTR_ERR(bh);
4887         }
4888         if (hlock != NULL)
4889                 ldiskfs_htree_unlock(hlock);
4890         else
4891                 up_write(&obj->oo_ext_idx_sem);
4892
4893         GOTO(out, rc);
4894
4895 out:
4896         LASSERT(osd_invariant(obj));
4897         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
4898         RETURN(rc);
4899 }
4900
4901 /**
4902  *      Lookup index for \a key and copy record to \a rec.
4903  *
4904  *      \param  dt      osd index object
4905  *      \param  key     key for index
4906  *      \param  rec     record reference
4907  *
4908  *      \retval  +ve  success : exact mach
4909  *      \retval  0    return record with key not greater than \a key
4910  *      \retval -ve   failure
4911  */
4912 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
4913                                 struct dt_rec *rec, const struct dt_key *key)
4914 {
4915         struct osd_object      *obj = osd_dt_obj(dt);
4916         struct iam_path_descr  *ipd;
4917         struct iam_container   *bag = &obj->oo_dir->od_container;
4918         struct osd_thread_info *oti = osd_oti_get(env);
4919         struct iam_iterator    *it = &oti->oti_idx_it;
4920         struct iam_rec         *iam_rec;
4921         int                     rc;
4922         ENTRY;
4923
4924         if (!dt_object_exists(dt))
4925                 RETURN(-ENOENT);
4926
4927         LASSERT(osd_invariant(obj));
4928         LASSERT(!dt_object_remote(dt));
4929         LASSERT(bag->ic_object == obj->oo_inode);
4930
4931         ipd = osd_idx_ipd_get(env, bag);
4932         if (IS_ERR(ipd))
4933                 RETURN(-ENOMEM);
4934
4935         /* got ipd now we can start iterator. */
4936         iam_it_init(it, bag, 0, ipd);
4937
4938         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
4939                 /* swab quota uid/gid provided by caller */
4940                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4941                 key = (const struct dt_key *)&oti->oti_quota_id;
4942         }
4943
4944         rc = iam_it_get(it, (struct iam_key *)key);
4945         if (rc >= 0) {
4946                 if (S_ISDIR(obj->oo_inode->i_mode))
4947                         iam_rec = (struct iam_rec *)oti->oti_ldp;
4948                 else
4949                         iam_rec = (struct iam_rec *) rec;
4950
4951                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
4952
4953                 if (S_ISDIR(obj->oo_inode->i_mode))
4954                         osd_fid_unpack((struct lu_fid *) rec,
4955                                        (struct osd_fid_pack *)iam_rec);
4956                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
4957                         osd_quota_unpack(obj, rec);
4958         }
4959
4960         iam_it_put(it);
4961         iam_it_fini(it);
4962         osd_ipd_put(env, bag, ipd);
4963
4964         LINVRNT(osd_invariant(obj));
4965
4966         RETURN(rc);
4967 }
4968
4969 static int osd_index_declare_iam_insert(const struct lu_env *env,
4970                                         struct dt_object *dt,
4971                                         const struct dt_rec *rec,
4972                                         const struct dt_key *key,
4973                                         struct thandle *handle)
4974 {
4975         struct osd_thandle *oh;
4976
4977         LASSERT(handle != NULL);
4978
4979         oh = container_of0(handle, struct osd_thandle, ot_super);
4980         LASSERT(oh->ot_handle == NULL);
4981
4982         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4983                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4984
4985         return 0;
4986 }
4987
4988 /**
4989  *      Inserts (key, value) pair in \a dt index object.
4990  *
4991  *      \param  dt      osd index object
4992  *      \param  key     key for index
4993  *      \param  rec     record reference
4994  *      \param  th      transaction handler
4995  *
4996  *      \retval  0  success
4997  *      \retval -ve failure
4998  */
4999 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
5000                                 const struct dt_rec *rec,
5001                                 const struct dt_key *key, struct thandle *th,
5002                                 int ignore_quota)
5003 {
5004         struct osd_object     *obj = osd_dt_obj(dt);
5005         struct iam_path_descr *ipd;
5006         struct osd_thandle    *oh;
5007         struct iam_container  *bag;
5008         struct osd_thread_info *oti = osd_oti_get(env);
5009         struct iam_rec         *iam_rec;
5010         int                     rc;
5011         ENTRY;
5012
5013         if (!dt_object_exists(dt))
5014                 RETURN(-ENOENT);
5015
5016         LINVRNT(osd_invariant(obj));
5017         LASSERT(!dt_object_remote(dt));
5018
5019         bag = &obj->oo_dir->od_container;
5020         LASSERT(bag->ic_object == obj->oo_inode);
5021         LASSERT(th != NULL);
5022
5023         osd_trans_exec_op(env, th, OSD_OT_INSERT);
5024
5025         ipd = osd_idx_ipd_get(env, bag);
5026         if (unlikely(ipd == NULL))
5027                 RETURN(-ENOMEM);
5028
5029         oh = container_of0(th, struct osd_thandle, ot_super);
5030         LASSERT(oh->ot_handle != NULL);
5031         LASSERT(oh->ot_handle->h_transaction != NULL);
5032         if (S_ISDIR(obj->oo_inode->i_mode)) {
5033                 iam_rec = (struct iam_rec *)oti->oti_ldp;
5034                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
5035         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5036                 /* pack quota uid/gid */
5037                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5038                 key = (const struct dt_key *)&oti->oti_quota_id;
5039                 /* pack quota record */
5040                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
5041                 iam_rec = (struct iam_rec *)rec;
5042         } else {
5043                 iam_rec = (struct iam_rec *)rec;
5044         }
5045
5046         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
5047                         iam_rec, ipd);
5048         osd_ipd_put(env, bag, ipd);
5049         LINVRNT(osd_invariant(obj));
5050         osd_trans_exec_check(env, th, OSD_OT_INSERT);
5051         RETURN(rc);
5052 }
5053
5054 /**
5055  * Calls ldiskfs_add_entry() to add directory entry
5056  * into the directory. This is required for
5057  * interoperability mode (b11826)
5058  *
5059  * \retval   0, on success
5060  * \retval -ve, on error
5061  */
5062 static int __osd_ea_add_rec(struct osd_thread_info *info,
5063                             struct osd_object *pobj, struct inode  *cinode,
5064                             const char *name, const struct lu_fid *fid,
5065                             struct htree_lock *hlock, struct thandle *th)
5066 {
5067         struct ldiskfs_dentry_param *ldp;
5068         struct dentry               *child;
5069         struct osd_thandle          *oth;
5070         int                          rc;
5071
5072         oth = container_of(th, struct osd_thandle, ot_super);
5073         LASSERT(oth->ot_handle != NULL);
5074         LASSERT(oth->ot_handle->h_transaction != NULL);
5075         LASSERT(pobj->oo_inode);
5076
5077         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
5078         if (unlikely(pobj->oo_inode ==
5079                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
5080                 ldp->edp_magic = 0;
5081         else
5082                 osd_get_ldiskfs_dirent_param(ldp, fid);
5083         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
5084         child->d_fsdata = (void *)ldp;
5085         ll_vfs_dq_init(pobj->oo_inode);
5086         rc = osd_ldiskfs_add_entry(info, osd_obj2dev(pobj), oth->ot_handle,
5087                                    child, cinode, hlock);
5088         if (rc == 0 && OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_TYPE)) {
5089                 struct ldiskfs_dir_entry_2      *de;
5090                 struct buffer_head              *bh;
5091                 int                              rc1;
5092
5093                 bh = osd_ldiskfs_find_entry(pobj->oo_inode, &child->d_name, &de,
5094                                             NULL, hlock);
5095                 if (!IS_ERR(bh)) {
5096                         rc1 = ldiskfs_journal_get_write_access(oth->ot_handle,
5097                                                                bh);
5098                         if (rc1 == 0) {
5099                                 if (S_ISDIR(cinode->i_mode))
5100                                         de->file_type = LDISKFS_DIRENT_LUFID |
5101                                                         LDISKFS_FT_REG_FILE;
5102                                 else
5103                                         de->file_type = LDISKFS_DIRENT_LUFID |
5104                                                         LDISKFS_FT_DIR;
5105                                 ldiskfs_handle_dirty_metadata(oth->ot_handle,
5106                                                               NULL, bh);
5107                         }
5108                         brelse(bh);
5109                 }
5110         }
5111
5112         RETURN(rc);
5113 }
5114
5115 /**
5116  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
5117  * into the directory.Also sets flags into osd object to
5118  * indicate dot and dotdot are created. This is required for
5119  * interoperability mode (b11826)
5120  *
5121  * \param dir   directory for dot and dotdot fixup.
5122  * \param obj   child object for linking
5123  *
5124  * \retval   0, on success
5125  * \retval -ve, on error
5126  */
5127 static int osd_add_dot_dotdot(struct osd_thread_info *info,
5128                               struct osd_object *dir,
5129                               struct inode *parent_dir, const char *name,
5130                               const struct lu_fid *dot_fid,
5131                               const struct lu_fid *dot_dot_fid,
5132                               struct thandle *th)
5133 {
5134         struct inode                *inode = dir->oo_inode;
5135         struct osd_thandle          *oth;
5136         int result = 0;
5137
5138         oth = container_of(th, struct osd_thandle, ot_super);
5139         LASSERT(oth->ot_handle->h_transaction != NULL);
5140         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
5141
5142         if (strcmp(name, dot) == 0) {
5143                 if (dir->oo_compat_dot_created) {
5144                         result = -EEXIST;
5145                 } else {
5146                         LASSERT(inode->i_ino == parent_dir->i_ino);
5147                         dir->oo_compat_dot_created = 1;
5148                         result = 0;
5149                 }
5150         } else if (strcmp(name, dotdot) == 0) {
5151                 if (!dir->oo_compat_dot_created)
5152                         return -EINVAL;
5153                 /* in case of rename, dotdot is already created */
5154                 if (dir->oo_compat_dotdot_created) {
5155                         return __osd_ea_add_rec(info, dir, parent_dir, name,
5156                                                 dot_dot_fid, NULL, th);
5157                 }
5158
5159                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
5160                         struct lu_fid tfid = *dot_dot_fid;
5161
5162                         tfid.f_oid--;
5163                         result = osd_add_dot_dotdot_internal(info,
5164                                         dir->oo_inode, parent_dir, dot_fid,
5165                                         &tfid, oth);
5166                 } else {
5167                         result = osd_add_dot_dotdot_internal(info,
5168                                         dir->oo_inode, parent_dir, dot_fid,
5169                                         dot_dot_fid, oth);
5170                 }
5171
5172                 if (result == 0)
5173                         dir->oo_compat_dotdot_created = 1;
5174         }
5175
5176         return result;
5177 }
5178
5179
5180 /**
5181  * It will call the appropriate osd_add* function and return the
5182  * value, return by respective functions.
5183  */
5184 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
5185                           struct inode *cinode, const char *name,
5186                           const struct lu_fid *fid, struct thandle *th)
5187 {
5188         struct osd_thread_info *info   = osd_oti_get(env);
5189         struct htree_lock      *hlock;
5190         int                     rc;
5191
5192         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
5193
5194         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
5195                                                    name[2] =='\0'))) {
5196                 if (hlock != NULL) {
5197                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5198                                            pobj->oo_inode, 0);
5199                 } else {
5200                         down_write(&pobj->oo_ext_idx_sem);
5201                 }
5202
5203                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
5204                                         lu_object_fid(&pobj->oo_dt.do_lu),
5205                                         fid, th);
5206         } else {
5207                 if (hlock != NULL) {
5208                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5209                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
5210                 } else {
5211                         down_write(&pobj->oo_ext_idx_sem);
5212                 }
5213
5214                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
5215                         struct lu_fid *tfid = &info->oti_fid;
5216
5217                         *tfid = *fid;
5218                         tfid->f_ver = ~0;
5219                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
5220                                               tfid, hlock, th);
5221                 } else {
5222                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
5223                                               hlock, th);
5224                 }
5225         }
5226         if (hlock != NULL)
5227                 ldiskfs_htree_unlock(hlock);
5228         else
5229                 up_write(&pobj->oo_ext_idx_sem);
5230
5231         return rc;
5232 }
5233
5234 static int
5235 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
5236                       struct osd_idmap_cache *oic)
5237 {
5238         struct lustre_scrub *scrub = &dev->od_scrub.os_scrub;
5239         struct lu_fid *fid = &oic->oic_fid;
5240         struct osd_inode_id *id = &oic->oic_lid;
5241         struct inode *inode = NULL;
5242         int once = 0;
5243         bool insert;
5244         int rc;
5245         ENTRY;
5246
5247         if (!fid_is_norm(fid) && !fid_is_igif(fid))
5248                 RETURN(0);
5249
5250         if (thread_is_running(&scrub->os_thread) &&
5251             scrub->os_pos_current > id->oii_ino)
5252                 RETURN(0);
5253
5254         if (dev->od_auto_scrub_interval == AS_NEVER ||
5255             ktime_get_real_seconds() <
5256             scrub->os_file.sf_time_last_complete + dev->od_auto_scrub_interval)
5257                 RETURN(0);
5258
5259 again:
5260         rc = osd_oi_lookup(oti, dev, fid, &oti->oti_id, 0);
5261         if (rc == -ENOENT) {
5262                 __u32 gen = id->oii_gen;
5263
5264                 insert = true;
5265                 if (inode != NULL)
5266                         goto trigger;
5267
5268                 inode = osd_iget(oti, dev, id);
5269                 /* The inode has been removed (by race maybe). */
5270                 if (IS_ERR(inode)) {
5271                         rc = PTR_ERR(inode);
5272
5273                         RETURN(rc == -ESTALE ? -ENOENT : rc);
5274                 }
5275
5276                 /* The OI mapping is lost. */
5277                 if (gen != OSD_OII_NOGEN)
5278                         goto trigger;
5279
5280                 /* The inode may has been reused by others, we do not know,
5281                  * leave it to be handled by subsequent osd_fid_lookup(). */
5282                 GOTO(out, rc = 0);
5283         } else if (rc || osd_id_eq(id, &oti->oti_id)) {
5284                 GOTO(out, rc);
5285         }
5286
5287         insert = false;
5288
5289 trigger:
5290         if (thread_is_running(&scrub->os_thread)) {
5291                 if (inode == NULL) {
5292                         inode = osd_iget(oti, dev, id);
5293                         /* The inode has been removed (by race maybe). */
5294                         if (IS_ERR(inode)) {
5295                                 rc = PTR_ERR(inode);
5296
5297                                 RETURN(rc == -ESTALE ? -ENOENT : rc);
5298                         }
5299                 }
5300
5301                 rc = osd_oii_insert(dev, oic, insert);
5302                 /* There is race condition between osd_oi_lookup and OI scrub.
5303                  * The OI scrub finished just after osd_oi_lookup() failure.
5304                  * Under such case, it is unnecessary to trigger OI scrub again,
5305                  * but try to call osd_oi_lookup() again. */
5306                 if (unlikely(rc == -EAGAIN))
5307                         goto again;
5308
5309                 if (!S_ISDIR(inode->i_mode))
5310                         rc = 0;
5311                 else
5312                         rc = osd_check_lmv(oti, dev, inode, oic);
5313
5314                 GOTO(out, rc);
5315         }
5316
5317         if (dev->od_auto_scrub_interval != AS_NEVER && ++once == 1) {
5318                 rc = osd_scrub_start(oti->oti_env, dev, SS_AUTO_PARTIAL |
5319                                      SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT);
5320                 CDEBUG(D_LFSCK | D_CONSOLE | D_WARNING,
5321                        "%s: trigger partial OI scrub for RPC inconsistency "
5322                        "checking FID "DFID": rc = %d\n",
5323                        osd_dev2name(dev), PFID(fid), rc);
5324                 if (rc == 0 || rc == -EALREADY)
5325                         goto again;
5326         }
5327
5328         GOTO(out, rc);
5329
5330 out:
5331         if (inode)
5332                 iput(inode);
5333
5334         RETURN(rc);
5335 }
5336
5337 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
5338                                struct osd_device *dev,
5339                                struct osd_idmap_cache *oic,
5340                                struct lu_fid *fid, __u32 ino)
5341 {
5342         struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
5343         struct inode *inode;
5344         int rc;
5345
5346         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
5347         inode = osd_iget(oti, dev, &oic->oic_lid);
5348         if (IS_ERR(inode)) {
5349                 fid_zero(&oic->oic_fid);
5350                 return PTR_ERR(inode);
5351         }
5352
5353         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, loa);
5354         iput(inode);
5355         if (rc != 0)
5356                 fid_zero(&oic->oic_fid);
5357         else
5358                 *fid = oic->oic_fid = loa->loa_lma.lma_self_fid;
5359         return rc;
5360 }
5361
5362 void osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
5363                       struct osd_inode_id *id, const struct lu_fid *fid)
5364 {
5365         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
5366                id->oii_ino, id->oii_gen, info);
5367         info->oti_cache.oic_lid = *id;
5368         info->oti_cache.oic_fid = *fid;
5369         info->oti_cache.oic_dev = osd;
5370 }
5371
5372 /**
5373  * Get parent FID from the linkEA.
5374  *
5375  * For a directory which parent resides on remote MDT, to satisfy the
5376  * local e2fsck, we insert it into the /REMOTE_PARENT_DIR locally. On
5377  * the other hand, to make the lookup(..) on the directory can return
5378  * the real parent FID, we append the real parent FID after its ".."
5379  * name entry in the /REMOTE_PARENT_DIR.
5380  *
5381  * Unfortunately, such PFID-in-dirent cannot be preserved via file-level
5382  * backup. So after the restore, we cannot get the right parent FID from
5383  * its ".." name entry in the /REMOTE_PARENT_DIR. Under such case, since
5384  * we have stored the real parent FID in the directory object's linkEA,
5385  * we can parse the linkEA for the real parent FID.
5386  *
5387  * \param[in] env       pointer to the thread context
5388  * \param[in] obj       pointer to the object to be handled
5389  * \param[out]fid       pointer to the buffer to hold the parent FID
5390  *
5391  * \retval              0 for getting the real parent FID successfully
5392  * \retval              negative error number on failure
5393  */
5394 static int osd_get_pfid_from_linkea(const struct lu_env *env,
5395                                     struct osd_object *obj,
5396                                     struct lu_fid *fid)
5397 {
5398         struct osd_thread_info  *oti    = osd_oti_get(env);
5399         struct lu_buf           *buf    = &oti->oti_big_buf;
5400         struct dentry           *dentry = &oti->oti_obj_dentry;
5401         struct inode            *inode  = obj->oo_inode;
5402         struct linkea_data       ldata  = { NULL };
5403         int                      rc;
5404         ENTRY;
5405
5406         fid_zero(fid);
5407         if (!S_ISDIR(inode->i_mode))
5408                 RETURN(-EIO);
5409
5410 again:
5411         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5412                              buf->lb_buf, buf->lb_len);
5413         if (rc == -ERANGE) {
5414                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5415                                      NULL, 0);
5416                 if (rc > 0) {
5417                         lu_buf_realloc(buf, rc);
5418                         if (buf->lb_buf == NULL)
5419                                 RETURN(-ENOMEM);
5420
5421                         goto again;
5422                 }
5423         }
5424
5425         if (unlikely(rc == 0))
5426                 RETURN(-ENODATA);
5427
5428         if (rc < 0)
5429                 RETURN(rc);
5430
5431         if (unlikely(buf->lb_buf == NULL)) {
5432                 lu_buf_realloc(buf, rc);
5433                 if (buf->lb_buf == NULL)
5434                         RETURN(-ENOMEM);
5435
5436                 goto again;
5437         }
5438
5439         ldata.ld_buf = buf;
5440         rc = linkea_init_with_rec(&ldata);
5441         if (!rc) {
5442                 linkea_first_entry(&ldata);
5443                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, NULL, fid);
5444         }
5445
5446         RETURN(rc);
5447 }
5448
5449 static int osd_verify_ent_by_linkea(const struct lu_env *env,
5450                                     struct inode *inode,
5451                                     const struct lu_fid *pfid,
5452                                     const char *name, const int namelen)
5453 {
5454         struct osd_thread_info *oti = osd_oti_get(env);
5455         struct lu_buf *buf = &oti->oti_big_buf;
5456         struct dentry *dentry = &oti->oti_obj_dentry;
5457         struct linkea_data ldata = { NULL };
5458         struct lu_name cname = { .ln_name = name,
5459                                  .ln_namelen = namelen };
5460         int rc;
5461         ENTRY;
5462
5463 again:
5464         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5465                              buf->lb_buf, buf->lb_len);
5466         if (rc == -ERANGE)
5467                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK, NULL, 0);
5468
5469         if (rc < 0)
5470                 RETURN(rc);
5471
5472         if (unlikely(rc == 0))
5473                 RETURN(-ENODATA);
5474
5475         if (buf->lb_len < rc) {
5476                 lu_buf_realloc(buf, rc);
5477                 if (buf->lb_buf == NULL)
5478                         RETURN(-ENOMEM);
5479
5480                 goto again;
5481         }
5482
5483         ldata.ld_buf = buf;
5484         rc = linkea_init_with_rec(&ldata);
5485         if (!rc)
5486                 rc = linkea_links_find(&ldata, &cname, pfid);
5487
5488         RETURN(rc);
5489 }
5490
5491 /**
5492  * Calls ->lookup() to find dentry. From dentry get inode and
5493  * read inode's ea to get fid. This is required for  interoperability
5494  * mode (b11826)
5495  *
5496  * \retval   0, on success
5497  * \retval -ve, on error
5498  */
5499 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
5500                              struct dt_rec *rec, const struct dt_key *key)
5501 {
5502         struct inode                    *dir    = obj->oo_inode;
5503         struct dentry                   *dentry;
5504         struct ldiskfs_dir_entry_2      *de;
5505         struct buffer_head              *bh;
5506         struct lu_fid                   *fid = (struct lu_fid *) rec;
5507         struct htree_lock               *hlock = NULL;
5508         int                             ino;
5509         int                             rc;
5510         ENTRY;
5511
5512         LASSERT(dir->i_op != NULL);
5513         LASSERT(dir->i_op->lookup != NULL);
5514
5515         dentry = osd_child_dentry_get(env, obj,
5516                                       (char *)key, strlen((char *)key));
5517
5518         if (obj->oo_hl_head != NULL) {
5519                 hlock = osd_oti_get(env)->oti_hlock;
5520                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5521                                    dir, LDISKFS_HLOCK_LOOKUP);
5522         } else {
5523                 down_read(&obj->oo_ext_idx_sem);
5524         }
5525
5526         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5527         if (!IS_ERR(bh)) {
5528                 struct osd_thread_info *oti = osd_oti_get(env);
5529                 struct osd_inode_id *id = &oti->oti_id;
5530                 struct osd_idmap_cache *oic = &oti->oti_cache;
5531                 struct osd_device *dev = osd_obj2dev(obj);
5532
5533                 ino = le32_to_cpu(de->inode);
5534                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
5535                         brelse(bh);
5536                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
5537                         GOTO(out, rc);
5538                 }
5539
5540                 rc = osd_get_fid_from_dentry(de, rec);
5541
5542                 /* done with de, release bh */
5543                 brelse(bh);
5544                 if (rc != 0) {
5545                         if (unlikely(ino == osd_remote_parent_ino(dev))) {
5546                                 const char *name = (const char *)key;
5547
5548                                 /* If the parent is on remote MDT, and there
5549                                  * is no FID-in-dirent, then we have to get
5550                                  * the parent FID from the linkEA.  */
5551                                 if (likely(strlen(name) == 2 &&
5552                                            name[0] == '.' && name[1] == '.'))
5553                                         rc = osd_get_pfid_from_linkea(env, obj,
5554                                                                       fid);
5555                         } else {
5556                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
5557                         }
5558                 } else {
5559                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5560                 }
5561
5562                 if (rc != 0 || osd_remote_fid(env, dev, fid)) {
5563                         fid_zero(&oic->oic_fid);
5564
5565                         GOTO(out, rc);
5566                 }
5567
5568                 osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id, fid);
5569                 rc = osd_consistency_check(oti, dev, oic);
5570                 if (rc == -ENOENT)
5571                         fid_zero(&oic->oic_fid);
5572                 else
5573                         /* Other error should not affect lookup result. */
5574                         rc = 0;
5575         } else {
5576                 rc = PTR_ERR(bh);
5577         }
5578
5579         GOTO(out, rc);
5580
5581 out:
5582         if (hlock != NULL)
5583                 ldiskfs_htree_unlock(hlock);
5584         else
5585                 up_read(&obj->oo_ext_idx_sem);
5586         return rc;
5587 }
5588
5589 static int osd_index_declare_ea_insert(const struct lu_env *env,
5590                                        struct dt_object *dt,
5591                                        const struct dt_rec *rec,
5592                                        const struct dt_key *key,
5593                                        struct thandle *handle)
5594 {
5595         struct osd_thandle      *oh;
5596         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
5597         struct dt_insert_rec    *rec1   = (struct dt_insert_rec *)rec;
5598         const struct lu_fid     *fid    = rec1->rec_fid;
5599         int                      credits, rc = 0;
5600         struct osd_idmap_cache  *idc;
5601         ENTRY;
5602
5603         LASSERT(!dt_object_remote(dt));
5604         LASSERT(handle != NULL);
5605         LASSERT(fid != NULL);
5606         LASSERT(rec1->rec_type != 0);
5607
5608         oh = container_of0(handle, struct osd_thandle, ot_super);
5609         LASSERT(oh->ot_handle == NULL);
5610
5611         credits = osd_dto_credits_noquota[DTO_INDEX_INSERT];
5612
5613         /* we can't call iget() while a transactions is running
5614          * (this can lead to a deadlock), but we need to know
5615          * inum and object type. so we find this information at
5616          * declaration and cache in per-thread info */
5617         idc = osd_idc_find_or_init(env, osd, fid);
5618         if (IS_ERR(idc))
5619                 RETURN(PTR_ERR(idc));
5620         if (idc->oic_remote) {
5621                 /* a reference to remote inode is represented by an
5622                  * agent inode which we have to create */
5623                 credits += osd_dto_credits_noquota[DTO_OBJECT_CREATE];
5624                 credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
5625         }
5626
5627         osd_trans_declare_op(env, oh, OSD_OT_INSERT, credits);
5628
5629         if (osd_dt_obj(dt)->oo_inode != NULL) {
5630                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
5631
5632                 /* We ignore block quota on meta pool (MDTs), so needn't
5633                  * calculate how many blocks will be consumed by this index
5634                  * insert */
5635                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
5636                                            i_gid_read(inode),
5637                                            i_projid_read(inode), 0,
5638                                            oh, osd_dt_obj(dt), NULL,
5639                                            OSD_QID_BLK);
5640                 if (rc)
5641                         RETURN(rc);
5642
5643 #ifdef HAVE_PROJECT_QUOTA
5644                 /* Reserve credits for local agent inode to transfer
5645                  * to 0, quota enforcement is ignored in this case.
5646                  */
5647                 if (idc->oic_remote &&
5648                     LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
5649                     i_projid_read(inode) != 0)
5650                         rc = osd_declare_attr_qid(env, osd_dt_obj(dt), oh,
5651                                                   0, i_projid_read(inode),
5652                                                   0, false, PRJQUOTA, true);
5653 #endif
5654         }
5655
5656
5657         RETURN(rc);
5658 }
5659
5660 /**
5661  * Index add function for interoperability mode (b11826).
5662  * It will add the directory entry.This entry is needed to
5663  * maintain name->fid mapping.
5664  *
5665  * \param key it is key i.e. file entry to be inserted
5666  * \param rec it is value of given key i.e. fid
5667  *
5668  * \retval   0, on success
5669  * \retval -ve, on error
5670  */
5671 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
5672                                const struct dt_rec *rec,
5673                                const struct dt_key *key, struct thandle *th,
5674                                int ignore_quota)
5675 {
5676         struct osd_object       *obj = osd_dt_obj(dt);
5677         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
5678         struct dt_insert_rec    *rec1   = (struct dt_insert_rec *)rec;
5679         const struct lu_fid     *fid    = rec1->rec_fid;
5680         const char              *name = (const char *)key;
5681         struct osd_thread_info  *oti   = osd_oti_get(env);
5682         struct inode            *child_inode = NULL;
5683         struct osd_idmap_cache  *idc;
5684         int                     rc;
5685         ENTRY;
5686
5687         if (!dt_object_exists(dt))
5688                 RETURN(-ENOENT);
5689
5690         LASSERT(osd_invariant(obj));
5691         LASSERT(!dt_object_remote(dt));
5692         LASSERT(th != NULL);
5693
5694         osd_trans_exec_op(env, th, OSD_OT_INSERT);
5695
5696         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!\n", PFID(fid));
5697
5698         idc = osd_idc_find(env, osd, fid);
5699         if (unlikely(idc == NULL)) {
5700                 /* this dt_insert() wasn't declared properly, so
5701                  * FID is missing in OI cache. we better do not
5702                  * lookup FID in FLDB/OI and don't risk to deadlock,
5703                  * but in some special cases (lfsck testing, etc)
5704                  * it's much simpler than fixing a caller */
5705                 CERROR("%s: "DFID" wasn't declared for insert\n",
5706                        osd_name(osd), PFID(fid));
5707                 dump_stack();
5708                 idc = osd_idc_find_or_init(env, osd, fid);
5709                 if (IS_ERR(idc))
5710                         RETURN(PTR_ERR(idc));
5711         }
5712
5713         if (idc->oic_remote) {
5714                 /* Insert remote entry */
5715                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
5716                         child_inode =
5717                         igrab(osd->od_mdt_map->omm_remote_parent->d_inode);
5718                 } else {
5719                         child_inode = osd_create_local_agent_inode(env, osd,
5720                                         obj, fid, rec1->rec_type & S_IFMT, th);
5721                         if (IS_ERR(child_inode))
5722                                 RETURN(PTR_ERR(child_inode));
5723                 }
5724         } else {
5725                 /* Insert local entry */
5726                 if (unlikely(idc->oic_lid.oii_ino == 0)) {
5727                         /* for a reason OI cache wasn't filled properly */
5728                         CERROR("%s: OIC for "DFID" isn't filled\n",
5729                                osd_name(osd), PFID(fid));
5730                         RETURN(-EINVAL);
5731                 }
5732                 child_inode = oti->oti_inode;
5733                 if (unlikely(child_inode == NULL)) {
5734                         struct ldiskfs_inode_info *lii;
5735                         OBD_ALLOC_PTR(lii);
5736                         if (lii == NULL)
5737                                 RETURN(-ENOMEM);
5738                         child_inode = oti->oti_inode = &lii->vfs_inode;
5739                 }
5740                 child_inode->i_sb = osd_sb(osd);
5741                 child_inode->i_ino = idc->oic_lid.oii_ino;
5742                 child_inode->i_mode = rec1->rec_type & S_IFMT;
5743         }
5744
5745         rc = osd_ea_add_rec(env, obj, child_inode, name, fid, th);
5746
5747         CDEBUG(D_INODE, "parent %lu insert %s:%lu rc = %d\n",
5748                obj->oo_inode->i_ino, name, child_inode->i_ino, rc);
5749
5750         if (child_inode && child_inode != oti->oti_inode)
5751                 iput(child_inode);
5752         LASSERT(osd_invariant(obj));
5753         osd_trans_exec_check(env, th, OSD_OT_INSERT);
5754         RETURN(rc);
5755 }
5756
5757 /**
5758  *  Initialize osd Iterator for given osd index object.
5759  *
5760  *  \param  dt      osd index object
5761  */
5762
5763 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
5764                                      struct dt_object *dt,
5765                                      __u32 unused)
5766 {
5767         struct osd_it_iam      *it;
5768         struct osd_object      *obj = osd_dt_obj(dt);
5769         struct lu_object       *lo  = &dt->do_lu;
5770         struct iam_path_descr  *ipd;
5771         struct iam_container   *bag = &obj->oo_dir->od_container;
5772
5773         if (!dt_object_exists(dt))
5774                 return ERR_PTR(-ENOENT);
5775
5776         OBD_ALLOC_PTR(it);
5777         if (it == NULL)
5778                 return ERR_PTR(-ENOMEM);
5779
5780         ipd = osd_it_ipd_get(env, bag);
5781         if (likely(ipd != NULL)) {
5782                 it->oi_obj = obj;
5783                 it->oi_ipd = ipd;
5784                 lu_object_get(lo);
5785                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
5786                 return (struct dt_it *)it;
5787         } else {
5788                 OBD_FREE_PTR(it);
5789                 return ERR_PTR(-ENOMEM);
5790         }
5791 }
5792
5793 /**
5794  * free given Iterator.
5795  */
5796 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
5797 {
5798         struct osd_it_iam       *it  = (struct osd_it_iam *)di;
5799         struct osd_object       *obj = it->oi_obj;
5800
5801         iam_it_fini(&it->oi_it);
5802         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
5803         osd_object_put(env, obj);
5804         OBD_FREE_PTR(it);
5805 }
5806
5807 /**
5808  *  Move Iterator to record specified by \a key
5809  *
5810  *  \param  di      osd iterator
5811  *  \param  key     key for index
5812  *
5813  *  \retval +ve  di points to record with least key not larger than key
5814  *  \retval  0   di points to exact matched key
5815  *  \retval -ve  failure
5816  */
5817
5818 static int osd_it_iam_get(const struct lu_env *env,
5819                           struct dt_it *di, const struct dt_key *key)
5820 {
5821         struct osd_thread_info  *oti = osd_oti_get(env);
5822         struct osd_it_iam       *it = (struct osd_it_iam *)di;
5823
5824         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
5825                 /* swab quota uid/gid */
5826                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5827                 key = (struct dt_key *)&oti->oti_quota_id;
5828         }
5829
5830         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
5831 }
5832
5833 /**
5834  *  Release Iterator
5835  *
5836  *  \param  di      osd iterator
5837  */
5838 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
5839 {
5840         struct osd_it_iam *it = (struct osd_it_iam *)di;
5841
5842         iam_it_put(&it->oi_it);
5843 }
5844
5845 /**
5846  *  Move iterator by one record
5847  *
5848  *  \param  di      osd iterator
5849  *
5850  *  \retval +1   end of container reached
5851  *  \retval  0   success
5852  *  \retval -ve  failure
5853  */
5854
5855 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
5856 {
5857         struct osd_it_iam *it = (struct osd_it_iam *)di;
5858
5859         return iam_it_next(&it->oi_it);
5860 }
5861
5862 /**
5863  * Return pointer to the key under iterator.
5864  */
5865
5866 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
5867                                  const struct dt_it *di)
5868 {
5869         struct osd_thread_info *oti = osd_oti_get(env);
5870         struct osd_it_iam      *it = (struct osd_it_iam *)di;
5871         struct osd_object      *obj = it->oi_obj;
5872         struct dt_key          *key;
5873
5874         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
5875
5876         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
5877                 /* swab quota uid/gid */
5878                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
5879                 key = (struct dt_key *)&oti->oti_quota_id;
5880         }
5881
5882         return key;
5883 }
5884
5885 /**
5886  * Return size of key under iterator (in bytes)
5887  */
5888
5889 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
5890 {
5891         struct osd_it_iam *it = (struct osd_it_iam *)di;
5892
5893         return iam_it_key_size(&it->oi_it);
5894 }
5895
5896 static inline void
5897 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
5898 {
5899         /* check if file type is required */
5900         if (ent->lde_attrs & LUDA_TYPE) {
5901                 struct luda_type *lt;
5902                 int align = sizeof(*lt) - 1;
5903
5904                 len = (len + align) & ~align;
5905                 lt = (struct luda_type *)(ent->lde_name + len);
5906                 lt->lt_type = cpu_to_le16(DTTOIF(type));
5907         }
5908
5909         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
5910 }
5911
5912 /**
5913  * build lu direct from backend fs dirent.
5914  */
5915
5916 static inline void
5917 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
5918                    char *name, __u16 namelen, __u16 type, __u32 attr)
5919 {
5920         ent->lde_attrs = attr | LUDA_FID;
5921         fid_cpu_to_le(&ent->lde_fid, fid);
5922
5923         ent->lde_hash = cpu_to_le64(offset);
5924         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
5925
5926         strncpy(ent->lde_name, name, namelen);
5927         ent->lde_name[namelen] = '\0';
5928         ent->lde_namelen = cpu_to_le16(namelen);
5929
5930         /* append lustre attributes */
5931         osd_it_append_attrs(ent, namelen, type);
5932 }
5933
5934 /**
5935  * Return pointer to the record under iterator.
5936  */
5937 static int osd_it_iam_rec(const struct lu_env *env,
5938                           const struct dt_it *di,
5939                           struct dt_rec *dtrec, __u32 attr)
5940 {
5941         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
5942         struct osd_thread_info *info = osd_oti_get(env);
5943         ENTRY;
5944
5945         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
5946                 const struct osd_fid_pack *rec;
5947                 struct lu_fid             *fid = &info->oti_fid;
5948                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
5949                 char                      *name;
5950                 int                        namelen;
5951                 __u64                      hash;
5952                 int                        rc;
5953
5954                 name = (char *)iam_it_key_get(&it->oi_it);
5955                 if (IS_ERR(name))
5956                         RETURN(PTR_ERR(name));
5957
5958                 namelen = iam_it_key_size(&it->oi_it);
5959
5960                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
5961                 if (IS_ERR(rec))
5962                         RETURN(PTR_ERR(rec));
5963
5964                 rc = osd_fid_unpack(fid, rec);
5965                 if (rc)
5966                         RETURN(rc);
5967
5968                 hash = iam_it_store(&it->oi_it);
5969
5970                 /* IAM does not store object type in IAM index (dir) */
5971                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
5972                                    0, LUDA_FID);
5973         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
5974                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
5975                            (struct iam_rec *)dtrec);
5976                 osd_quota_unpack(it->oi_obj, dtrec);
5977         } else {
5978                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
5979                            (struct iam_rec *)dtrec);
5980         }
5981
5982         RETURN(0);
5983 }
5984
5985 /**
5986  * Returns cookie for current Iterator position.
5987  */
5988 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
5989 {
5990         struct osd_it_iam *it = (struct osd_it_iam *)di;
5991
5992         return iam_it_store(&it->oi_it);
5993 }
5994
5995 /**
5996  * Restore iterator from cookie.
5997  *
5998  * \param  di      osd iterator
5999  * \param  hash    Iterator location cookie
6000  *
6001  * \retval +ve  di points to record with least key not larger than key.
6002  * \retval  0   di points to exact matched key
6003  * \retval -ve  failure
6004  */
6005
6006 static int osd_it_iam_load(const struct lu_env *env,
6007                            const struct dt_it *di, __u64 hash)
6008 {
6009         struct osd_it_iam *it = (struct osd_it_iam *)di;
6010
6011         return iam_it_load(&it->oi_it, hash);
6012 }
6013
6014 static const struct dt_index_operations osd_index_iam_ops = {
6015         .dio_lookup         = osd_index_iam_lookup,
6016         .dio_declare_insert = osd_index_declare_iam_insert,
6017         .dio_insert         = osd_index_iam_insert,
6018         .dio_declare_delete = osd_index_declare_iam_delete,
6019         .dio_delete         = osd_index_iam_delete,
6020         .dio_it     = {
6021                 .init     = osd_it_iam_init,
6022                 .fini     = osd_it_iam_fini,
6023                 .get      = osd_it_iam_get,
6024                 .put      = osd_it_iam_put,
6025                 .next     = osd_it_iam_next,
6026                 .key      = osd_it_iam_key,
6027                 .key_size = osd_it_iam_key_size,
6028                 .rec      = osd_it_iam_rec,
6029                 .store    = osd_it_iam_store,
6030                 .load     = osd_it_iam_load
6031         }
6032 };
6033
6034
6035 /**
6036  * Creates or initializes iterator context.
6037  *
6038  * \retval struct osd_it_ea, iterator structure on success
6039  *
6040  */
6041 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
6042                                     struct dt_object *dt,
6043                                     __u32 attr)
6044 {
6045         struct osd_object       *obj  = osd_dt_obj(dt);
6046         struct osd_thread_info  *info = osd_oti_get(env);
6047         struct osd_it_ea        *oie;
6048         struct file             *file;
6049         struct lu_object        *lo   = &dt->do_lu;
6050         struct dentry           *obj_dentry;
6051         ENTRY;
6052
6053         if (!dt_object_exists(dt) || obj->oo_destroyed)
6054                 RETURN(ERR_PTR(-ENOENT));
6055
6056         OBD_SLAB_ALLOC_PTR_GFP(oie, osd_itea_cachep, GFP_NOFS);
6057         if (oie == NULL)
6058                 RETURN(ERR_PTR(-ENOMEM));
6059         obj_dentry = &oie->oie_dentry;
6060
6061         obj_dentry->d_inode = obj->oo_inode;
6062         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
6063         obj_dentry->d_name.hash = 0;
6064
6065         oie->oie_rd_dirent       = 0;
6066         oie->oie_it_dirent       = 0;
6067         oie->oie_dirent          = NULL;
6068         if (unlikely(!info->oti_it_ea_buf_used)) {
6069                 oie->oie_buf = info->oti_it_ea_buf;
6070                 info->oti_it_ea_buf_used = 1;
6071         } else {
6072                 OBD_ALLOC(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6073                 if (oie->oie_buf == NULL)
6074                         RETURN(ERR_PTR(-ENOMEM));
6075         }
6076         oie->oie_obj             = obj;
6077
6078         file = &oie->oie_file;
6079
6080         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
6081         if (attr & LUDA_64BITHASH)
6082                 file->f_mode    = FMODE_64BITHASH;
6083         else
6084                 file->f_mode    = FMODE_32BITHASH;
6085         file->f_path.dentry     = obj_dentry;
6086         file->f_mapping         = obj->oo_inode->i_mapping;
6087         file->f_op              = obj->oo_inode->i_fop;
6088         set_file_inode(file, obj->oo_inode);
6089
6090         lu_object_get(lo);
6091         RETURN((struct dt_it *) oie);
6092 }
6093
6094 /**
6095  * Destroy or finishes iterator context.
6096  *
6097  * \param di iterator structure to be destroyed
6098  */
6099 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
6100 {
6101         struct osd_thread_info  *info = osd_oti_get(env);
6102         struct osd_it_ea        *oie    = (struct osd_it_ea *)di;
6103         struct osd_object       *obj    = oie->oie_obj;
6104         struct inode            *inode  = obj->oo_inode;
6105
6106         ENTRY;
6107         oie->oie_file.f_op->release(inode, &oie->oie_file);
6108         osd_object_put(env, obj);
6109         if (unlikely(oie->oie_buf != info->oti_it_ea_buf))
6110                 OBD_FREE(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6111         else
6112                 info->oti_it_ea_buf_used = 0;
6113         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
6114         EXIT;
6115 }
6116
6117 /**
6118  * It position the iterator at given key, so that next lookup continues from
6119  * that key Or it is similar to dio_it->load() but based on a key,
6120  * rather than file position.
6121  *
6122  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
6123  * to the beginning.
6124  *
6125  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
6126  */
6127 static int osd_it_ea_get(const struct lu_env *env,
6128                          struct dt_it *di, const struct dt_key *key)
6129 {
6130         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
6131
6132         ENTRY;
6133         LASSERT(((const char *)key)[0] == '\0');
6134         it->oie_file.f_pos      = 0;
6135         it->oie_rd_dirent       = 0;
6136         it->oie_it_dirent       = 0;
6137         it->oie_dirent          = NULL;
6138
6139         RETURN(+1);
6140 }
6141
6142 /**
6143  * Does nothing
6144  */
6145 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
6146 {
6147 }
6148
6149 struct osd_filldir_cbs {
6150 #ifdef HAVE_DIR_CONTEXT
6151         struct dir_context ctx;
6152 #endif
6153         struct osd_it_ea  *it;
6154 };
6155 /**
6156  * It is called internally by ->readdir(). It fills the
6157  * iterator's in-memory data structure with required
6158  * information i.e. name, namelen, rec_size etc.
6159  *
6160  * \param buf in which information to be filled in.
6161  * \param name name of the file in given dir
6162  *
6163  * \retval 0 on success
6164  * \retval 1 on buffer full
6165  */
6166 #ifdef HAVE_FILLDIR_USE_CTX
6167 static int osd_ldiskfs_filldir(struct dir_context *buf,
6168 #else
6169 static int osd_ldiskfs_filldir(void *buf,
6170 #endif
6171                                const char *name, int namelen,
6172                                loff_t offset, __u64 ino, unsigned d_type)
6173 {
6174         struct osd_it_ea        *it   =
6175                 ((struct osd_filldir_cbs *)buf)->it;
6176         struct osd_object       *obj  = it->oie_obj;
6177         struct osd_it_ea_dirent *ent  = it->oie_dirent;
6178         struct lu_fid           *fid  = &ent->oied_fid;
6179         struct osd_fid_pack     *rec;
6180         ENTRY;
6181
6182         /* this should never happen */
6183         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
6184                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
6185                 RETURN(-EIO);
6186         }
6187
6188         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
6189             OSD_IT_EA_BUFSIZE)
6190                 RETURN(1);
6191
6192         /* "." is just the object itself. */
6193         if (namelen == 1 && name[0] == '.') {
6194                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
6195         } else if (d_type & LDISKFS_DIRENT_LUFID) {
6196                 rec = (struct osd_fid_pack*) (name + namelen + 1);
6197                 if (osd_fid_unpack(fid, rec) != 0)
6198                         fid_zero(fid);
6199         } else {
6200                 fid_zero(fid);
6201         }
6202         d_type &= ~LDISKFS_DIRENT_LUFID;
6203
6204         /* NOT export local root. */
6205         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
6206                 ino = obj->oo_inode->i_ino;
6207                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
6208         }
6209
6210         ent->oied_ino     = ino;
6211         ent->oied_off     = offset;
6212         ent->oied_namelen = namelen;
6213         ent->oied_type    = d_type;
6214
6215         memcpy(ent->oied_name, name, namelen);
6216
6217         it->oie_rd_dirent++;
6218         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
6219         RETURN(0);
6220 }
6221
6222 /**
6223  * Calls ->readdir() to load a directory entry at a time
6224  * and stored it in iterator's in-memory data structure.
6225  *
6226  * \param di iterator's in memory structure
6227  *
6228  * \retval   0 on success
6229  * \retval -ve on error
6230  * \retval +1 reach the end of entry
6231  */
6232 static int osd_ldiskfs_it_fill(const struct lu_env *env,
6233                                const struct dt_it *di)
6234 {
6235         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
6236         struct osd_object  *obj   = it->oie_obj;
6237         struct inode       *inode = obj->oo_inode;
6238         struct htree_lock  *hlock = NULL;
6239         struct file        *filp  = &it->oie_file;
6240         int                 rc = 0;
6241         struct osd_filldir_cbs buf = {
6242 #ifdef HAVE_DIR_CONTEXT
6243                 .ctx.actor = osd_ldiskfs_filldir,
6244 #endif
6245                 .it = it
6246         };
6247
6248         ENTRY;
6249         it->oie_dirent = it->oie_buf;
6250         it->oie_rd_dirent = 0;
6251
6252         if (obj->oo_hl_head != NULL) {
6253                 hlock = osd_oti_get(env)->oti_hlock;
6254                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
6255                                    inode, LDISKFS_HLOCK_READDIR);
6256         } else {
6257                 down_read(&obj->oo_ext_idx_sem);
6258         }
6259
6260 #ifdef HAVE_DIR_CONTEXT
6261         buf.ctx.pos = filp->f_pos;
6262         rc = inode->i_fop->iterate(filp, &buf.ctx);
6263         filp->f_pos = buf.ctx.pos;
6264 #else
6265         rc = inode->i_fop->readdir(filp, &buf, osd_ldiskfs_filldir);
6266 #endif
6267
6268         if (hlock != NULL)
6269                 ldiskfs_htree_unlock(hlock);
6270         else
6271                 up_read(&obj->oo_ext_idx_sem);
6272
6273         if (it->oie_rd_dirent == 0) {
6274                 /*If it does not get any dirent, it means it has been reached
6275                  *to the end of the dir */
6276                 it->oie_file.f_pos = ldiskfs_get_htree_eof(&it->oie_file);
6277                 if (rc == 0)
6278                         rc = 1;
6279         } else {
6280                 it->oie_dirent = it->oie_buf;
6281                 it->oie_it_dirent = 1;
6282         }
6283
6284         RETURN(rc);
6285 }
6286
6287 /**
6288  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
6289  * to load a directory entry at a time and stored it in
6290  * iterator's in-memory data structure.
6291  *
6292  * \param di iterator's in memory structure
6293  *
6294  * \retval +ve iterator reached to end
6295  * \retval   0 iterator not reached to end
6296  * \retval -ve on error
6297  */
6298 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
6299 {
6300         struct osd_it_ea *it = (struct osd_it_ea *)di;
6301         int rc;
6302
6303         ENTRY;
6304
6305         if (it->oie_it_dirent < it->oie_rd_dirent) {
6306                 it->oie_dirent =
6307                         (void *) it->oie_dirent +
6308                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
6309                                        it->oie_dirent->oied_namelen);
6310                 it->oie_it_dirent++;
6311                 RETURN(0);
6312         } else {
6313                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
6314                         rc = +1;
6315                 else
6316                         rc = osd_ldiskfs_it_fill(env, di);
6317         }
6318
6319         RETURN(rc);
6320 }
6321
6322 /**
6323  * Returns the key at current position from iterator's in memory structure.
6324  *
6325  * \param di iterator's in memory structure
6326  *
6327  * \retval key i.e. struct dt_key on success
6328  */
6329 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
6330                                     const struct dt_it *di)
6331 {
6332         struct osd_it_ea *it = (struct osd_it_ea *)di;
6333
6334         return (struct dt_key *)it->oie_dirent->oied_name;
6335 }
6336
6337 /**
6338  * Returns the key's size at current position from iterator's in memory structure.
6339  *
6340  * \param di iterator's in memory structure
6341  *
6342  * \retval key_size i.e. struct dt_key on success
6343  */
6344 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
6345 {
6346         struct osd_it_ea *it = (struct osd_it_ea *)di;
6347
6348         return it->oie_dirent->oied_namelen;
6349 }
6350
6351 static inline bool osd_dotdot_has_space(struct ldiskfs_dir_entry_2 *de)
6352 {
6353         if (LDISKFS_DIR_REC_LEN(de) >=
6354             __LDISKFS_DIR_REC_LEN(2 + 1 + sizeof(struct osd_fid_pack)))
6355                 return true;
6356
6357         return false;
6358 }
6359
6360 static inline bool
6361 osd_dirent_has_space(struct ldiskfs_dir_entry_2 *de, __u16 namelen,
6362                      unsigned blocksize, bool dotdot)
6363 {
6364         if (dotdot)
6365                 return osd_dotdot_has_space(de);
6366
6367         if (ldiskfs_rec_len_from_disk(de->rec_len, blocksize) >=
6368             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
6369                 return true;
6370
6371         return false;
6372 }
6373
6374 static int
6375 osd_dirent_reinsert(const struct lu_env *env, struct osd_device *dev,
6376                     handle_t *jh, struct dentry *dentry,
6377                     const struct lu_fid *fid, struct buffer_head *bh,
6378                     struct ldiskfs_dir_entry_2 *de, struct htree_lock *hlock,
6379                     bool dotdot)
6380 {
6381         struct inode                *dir        = dentry->d_parent->d_inode;
6382         struct inode                *inode      = dentry->d_inode;
6383         struct osd_fid_pack         *rec;
6384         struct ldiskfs_dentry_param *ldp;
6385         int                          namelen    = dentry->d_name.len;
6386         int                          rc;
6387         struct osd_thread_info     *info        = osd_oti_get(env);
6388         ENTRY;
6389
6390         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
6391                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
6392                 RETURN(0);
6393
6394         /* There is enough space to hold the FID-in-dirent. */
6395         if (osd_dirent_has_space(de, namelen, dir->i_sb->s_blocksize, dotdot)) {
6396                 rc = ldiskfs_journal_get_write_access(jh, bh);
6397                 if (rc != 0)
6398                         RETURN(rc);
6399
6400                 de->name[namelen] = 0;
6401                 rec = (struct osd_fid_pack *)(de->name + namelen + 1);
6402                 rec->fp_len = sizeof(struct lu_fid) + 1;
6403                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
6404                 de->file_type |= LDISKFS_DIRENT_LUFID;
6405                 rc = ldiskfs_handle_dirty_metadata(jh, NULL, bh);
6406
6407                 RETURN(rc);
6408         }
6409
6410         LASSERT(!dotdot);
6411
6412         rc = ldiskfs_delete_entry(jh, dir, de, bh);
6413         if (rc != 0)
6414                 RETURN(rc);
6415
6416         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
6417         osd_get_ldiskfs_dirent_param(ldp, fid);
6418         dentry->d_fsdata = (void *)ldp;
6419         ll_vfs_dq_init(dir);
6420         rc = osd_ldiskfs_add_entry(info, dev, jh, dentry, inode, hlock);
6421         /* It is too bad, we cannot reinsert the name entry back.
6422          * That means we lose it! */
6423         if (rc != 0)
6424                 CDEBUG(D_LFSCK, "%s: fail to reinsert the dirent, "
6425                        "dir = %lu/%u, name = %.*s, "DFID": rc = %d\n",
6426                        osd_ino2name(inode),
6427                        dir->i_ino, dir->i_generation, namelen,
6428                        dentry->d_name.name, PFID(fid), rc);
6429
6430         RETURN(rc);
6431 }
6432
6433 static int
6434 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
6435                         struct osd_it_ea *it, struct lu_fid *fid,
6436                         struct osd_inode_id *id, __u32 *attr)
6437 {
6438         struct osd_thread_info     *info        = osd_oti_get(env);
6439         struct lustre_mdt_attrs    *lma         = &info->oti_ost_attrs.loa_lma;
6440         struct osd_device          *dev         = osd_obj2dev(obj);
6441         struct super_block         *sb          = osd_sb(dev);
6442         const char                 *devname     = osd_name(dev);
6443         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
6444         struct inode               *dir         = obj->oo_inode;
6445         struct htree_lock          *hlock       = NULL;
6446         struct buffer_head         *bh          = NULL;
6447         handle_t                   *jh          = NULL;
6448         struct ldiskfs_dir_entry_2 *de;
6449         struct dentry              *dentry;
6450         struct inode               *inode;
6451         const struct lu_fid *pfid = lu_object_fid(&obj->oo_dt.do_lu);
6452         int                         credits;
6453         int                         rc;
6454         bool                        dotdot      = false;
6455         bool                        dirty       = false;
6456         ENTRY;
6457
6458         if (ent->oied_name[0] == '.') {
6459                 if (ent->oied_namelen == 1)
6460                         RETURN(0);
6461
6462                 if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
6463                         dotdot = true;
6464         }
6465
6466         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
6467         inode = osd_iget(info, dev, id);
6468         if (IS_ERR(inode)) {
6469                 rc = PTR_ERR(inode);
6470                 if (rc == -ENOENT || rc == -ESTALE) {
6471                         /* Maybe dangling name entry, or
6472                          * corrupted directory entry. */
6473                         *attr |= LUDA_UNKNOWN;
6474                         rc = 0;
6475                 } else {
6476                         CDEBUG(D_LFSCK, "%s: fail to iget() for dirent "
6477                                "check_repair, dir = %lu/%u, name = %.*s, "
6478                                "ino = %llu, rc = %d\n",
6479                                devname, dir->i_ino, dir->i_generation,
6480                                ent->oied_namelen, ent->oied_name,
6481                                ent->oied_ino, rc);
6482                 }
6483
6484                 RETURN(rc);
6485         }
6486
6487         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
6488                                            ent->oied_namelen);
6489         rc = osd_get_lma(info, inode, dentry, &info->oti_ost_attrs);
6490         if (rc == -ENODATA || !fid_is_sane(&lma->lma_self_fid))
6491                 lma = NULL;
6492         else if (rc != 0)
6493                 GOTO(out, rc);
6494
6495         /* We need to ensure that the name entry is still valid.
6496          * Because it may be removed or renamed by other already.
6497          *
6498          * The unlink or rename operation will start journal before PDO lock,
6499          * so to avoid deadlock, here we need to start journal handle before
6500          * related PDO lock also. But because we do not know whether there
6501          * will be something to be repaired before PDO lock, we just start
6502          * journal without conditions.
6503          *
6504          * We may need to remove the name entry firstly, then insert back.
6505          * One credit is for user quota file update.
6506          * One credit is for group quota file update.
6507          * Two credits are for dirty inode. */
6508         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
6509                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
6510
6511         if (dev->od_dirent_journal != 0) {
6512
6513 again:
6514                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
6515                 if (IS_ERR(jh)) {
6516                         rc = PTR_ERR(jh);
6517                         CDEBUG(D_LFSCK, "%s: fail to start trans for dirent "
6518                                "check_repair, dir = %lu/%u, credits = %d, "
6519                                "name = %.*s, ino = %llu: rc = %d\n",
6520                                devname, dir->i_ino, dir->i_generation, credits,
6521                                ent->oied_namelen, ent->oied_name,
6522                                ent->oied_ino, rc);
6523
6524                         GOTO(out_inode, rc);
6525                 }
6526
6527                 if (obj->oo_hl_head != NULL) {
6528                         hlock = osd_oti_get(env)->oti_hlock;
6529                         /* "0" means exclusive lock for the whole directory.
6530                          * We need to prevent others access such name entry
6531                          * during the delete + insert. Neither HLOCK_ADD nor
6532                          * HLOCK_DEL cannot guarantee the atomicity. */
6533                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
6534                 } else {
6535                         down_write(&obj->oo_ext_idx_sem);
6536                 }
6537         } else {
6538                 if (obj->oo_hl_head != NULL) {
6539                         hlock = osd_oti_get(env)->oti_hlock;
6540                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
6541                                            LDISKFS_HLOCK_LOOKUP);
6542                 } else {
6543                         down_read(&obj->oo_ext_idx_sem);
6544                 }
6545         }
6546
6547         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
6548         if (IS_ERR(bh) || le32_to_cpu(de->inode) != inode->i_ino) {
6549                 *attr |= LUDA_IGNORE;
6550
6551                 GOTO(out, rc = 0);
6552         }
6553
6554         /* For dotdot entry, if there is not enough space to hold the
6555          * FID-in-dirent, just keep them there. It only happens when the
6556          * device upgraded from 1.8 or restored from MDT file-level backup.
6557          * For the whole directory, only dotdot entry have no FID-in-dirent
6558          * and needs to get FID from LMA when readdir, it will not affect the
6559          * performance much. */
6560         if (dotdot && !osd_dotdot_has_space(de)) {
6561                 *attr |= LUDA_UNKNOWN;
6562
6563                 GOTO(out, rc = 0);
6564         }
6565
6566         if (lma != NULL) {
6567                 if (lu_fid_eq(fid, &lma->lma_self_fid))
6568                         GOTO(out, rc = 0);
6569
6570                 if (unlikely(lma->lma_compat & LMAC_NOT_IN_OI)) {
6571                         struct lu_fid *tfid = &lma->lma_self_fid;
6572
6573                         if (likely(dotdot &&
6574                                    fid_seq(tfid) == FID_SEQ_LOCAL_FILE &&
6575                                    fid_oid(tfid) == REMOTE_PARENT_DIR_OID)) {
6576                                 /* It must be REMOTE_PARENT_DIR and as the
6577                                  * 'dotdot' entry of remote directory */
6578                                 *attr |= LUDA_IGNORE;
6579                         } else {
6580                                 CDEBUG(D_LFSCK, "%s: expect remote agent "
6581                                        "parent directory, but got %.*s under "
6582                                        "dir = %lu/%u with the FID "DFID"\n",
6583                                        devname, ent->oied_namelen,
6584                                        ent->oied_name, dir->i_ino,
6585                                        dir->i_generation, PFID(tfid));
6586
6587                                 *attr |= LUDA_UNKNOWN;
6588                         }
6589
6590                         GOTO(out, rc = 0);
6591                 }
6592         }
6593
6594         if (!fid_is_zero(fid)) {
6595                 rc = osd_verify_ent_by_linkea(env, inode, pfid, ent->oied_name,
6596                                               ent->oied_namelen);
6597                 if (rc == -ENOENT ||
6598                     (rc == -ENODATA &&
6599                      !(dev->od_scrub.os_scrub.os_file.sf_flags & SF_UPGRADE))) {
6600                         /* linkEA does not recognize the dirent entry,
6601                          * it may because the dirent entry corruption
6602                          * and points to other's inode. */
6603                         CDEBUG(D_LFSCK, "%s: the target inode does not "
6604                                "recognize the dirent, dir = %lu/%u, "
6605                                " name = %.*s, ino = %llu, "
6606                                DFID": rc = %d\n", devname, dir->i_ino,
6607                                dir->i_generation, ent->oied_namelen,
6608                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
6609                         *attr |= LUDA_UNKNOWN;
6610
6611                         GOTO(out, rc = 0);
6612                 }
6613
6614                 if (rc && rc != -ENODATA) {
6615                         CDEBUG(D_LFSCK, "%s: fail to verify FID in the dirent, "
6616                                "dir = %lu/%u, name = %.*s, ino = %llu, "
6617                                DFID": rc = %d\n", devname, dir->i_ino,
6618                                dir->i_generation, ent->oied_namelen,
6619                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
6620                         *attr |= LUDA_UNKNOWN;
6621
6622                         GOTO(out, rc = 0);
6623                 }
6624         }
6625
6626         if (lma != NULL) {
6627                 /* linkEA recognizes the dirent entry, the FID-in-LMA is
6628                  * valid, trusted, in spite of fid_is_sane(fid) or not. */
6629                 if (*attr & LUDA_VERIFY_DRYRUN) {
6630                         *fid = lma->lma_self_fid;
6631                         *attr |= LUDA_REPAIR;
6632
6633                         GOTO(out, rc = 0);
6634                 }
6635
6636                 if (jh == NULL) {
6637                         brelse(bh);
6638                         dev->od_dirent_journal = 1;
6639                         if (hlock != NULL) {
6640                                 ldiskfs_htree_unlock(hlock);
6641                                 hlock = NULL;
6642                         } else {
6643                                 up_read(&obj->oo_ext_idx_sem);
6644                         }
6645
6646                         goto again;
6647                 }
6648
6649                 *fid = lma->lma_self_fid;
6650                 dirty = true;
6651                 /* Update or append the FID-in-dirent. */
6652                 rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
6653                                          bh, de, hlock, dotdot);
6654                 if (rc == 0)
6655                         *attr |= LUDA_REPAIR;
6656                 else
6657                         CDEBUG(D_LFSCK, "%s: fail to re-insert FID after "
6658                                "the dirent, dir = %lu/%u, name = %.*s, "
6659                                "ino = %llu, "DFID": rc = %d\n",
6660                                devname, dir->i_ino, dir->i_generation,
6661                                ent->oied_namelen, ent->oied_name,
6662                                ent->oied_ino, PFID(fid), rc);
6663         } else {
6664                 /* lma is NULL, trust the FID-in-dirent if it is valid. */
6665                 if (*attr & LUDA_VERIFY_DRYRUN) {
6666                         if (fid_is_sane(fid)) {
6667                                 *attr |= LUDA_REPAIR;
6668                         } else if (dev->od_index == 0) {
6669                                 lu_igif_build(fid, inode->i_ino,
6670                                               inode->i_generation);
6671                                 *attr |= LUDA_UPGRADE;
6672                         }
6673
6674                         GOTO(out, rc = 0);
6675                 }
6676
6677                 if (jh == NULL) {
6678                         brelse(bh);
6679                         dev->od_dirent_journal = 1;
6680                         if (hlock != NULL) {
6681                                 ldiskfs_htree_unlock(hlock);
6682                                 hlock = NULL;
6683                         } else {
6684                                 up_read(&obj->oo_ext_idx_sem);
6685                         }
6686
6687                         goto again;
6688                 }
6689
6690                 dirty = true;
6691                 if (unlikely(fid_is_sane(fid))) {
6692                         /* FID-in-dirent exists, but FID-in-LMA is lost.
6693                          * Trust the FID-in-dirent, and add FID-in-LMA. */
6694                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
6695                         if (rc == 0)
6696                                 *attr |= LUDA_REPAIR;
6697                         else
6698                                 CDEBUG(D_LFSCK, "%s: fail to set LMA for "
6699                                        "update dirent, dir = %lu/%u, "
6700                                        "name = %.*s, ino = %llu, "
6701                                        DFID": rc = %d\n",
6702                                        devname, dir->i_ino, dir->i_generation,
6703                                        ent->oied_namelen, ent->oied_name,
6704                                        ent->oied_ino, PFID(fid), rc);
6705                 } else if (dev->od_index == 0) {
6706                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
6707                         /* It is probably IGIF object. Only aappend the
6708                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
6709                         rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
6710                                                  bh, de, hlock, dotdot);
6711                         if (rc == 0)
6712                                 *attr |= LUDA_UPGRADE;
6713                         else
6714                                 CDEBUG(D_LFSCK, "%s: fail to append IGIF "
6715                                        "after the dirent, dir = %lu/%u, "
6716                                        "name = %.*s, ino = %llu, "
6717                                        DFID": rc = %d\n",
6718                                        devname, dir->i_ino, dir->i_generation,
6719                                        ent->oied_namelen, ent->oied_name,
6720                                        ent->oied_ino, PFID(fid), rc);
6721                 }
6722         }
6723
6724         GOTO(out, rc);
6725
6726 out:
6727         if (!IS_ERR(bh))
6728                 brelse(bh);
6729         if (hlock != NULL) {
6730                 ldiskfs_htree_unlock(hlock);
6731         } else {
6732                 if (dev->od_dirent_journal != 0)
6733                         up_write(&obj->oo_ext_idx_sem);
6734                 else
6735                         up_read(&obj->oo_ext_idx_sem);
6736         }
6737
6738         if (jh != NULL)
6739                 ldiskfs_journal_stop(jh);
6740
6741 out_inode:
6742         iput(inode);
6743         if (rc >= 0 && !dirty)
6744                 dev->od_dirent_journal = 0;
6745
6746         return rc;
6747 }
6748
6749 /**
6750  * Returns the value at current position from iterator's in memory structure.
6751  *
6752  * \param di struct osd_it_ea, iterator's in memory structure
6753  * \param attr attr requested for dirent.
6754  * \param lde lustre dirent
6755  *
6756  * \retval   0 no error and \param lde has correct lustre dirent.
6757  * \retval -ve on error
6758  */
6759 static inline int osd_it_ea_rec(const struct lu_env *env,
6760                                 const struct dt_it *di,
6761                                 struct dt_rec *dtrec, __u32 attr)
6762 {
6763         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
6764         struct osd_object      *obj   = it->oie_obj;
6765         struct osd_device      *dev   = osd_obj2dev(obj);
6766         struct osd_thread_info *oti   = osd_oti_get(env);
6767         struct osd_inode_id    *id    = &oti->oti_id;
6768         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
6769         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
6770         __u32                   ino   = it->oie_dirent->oied_ino;
6771         int                     rc    = 0;
6772         ENTRY;
6773
6774         LASSERT(obj->oo_inode != dev->od_mdt_map->omm_remote_parent->d_inode);
6775
6776         if (attr & LUDA_VERIFY) {
6777                 if (unlikely(ino == osd_remote_parent_ino(dev))) {
6778                         attr |= LUDA_IGNORE;
6779                         /* If the parent is on remote MDT, and there
6780                          * is no FID-in-dirent, then we have to get
6781                          * the parent FID from the linkEA.  */
6782                         if (!fid_is_sane(fid) &&
6783                             it->oie_dirent->oied_namelen == 2 &&
6784                             it->oie_dirent->oied_name[0] == '.' &&
6785                             it->oie_dirent->oied_name[1] == '.')
6786                                 osd_get_pfid_from_linkea(env, obj, fid);
6787                 } else {
6788                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
6789                                                      &attr);
6790                 }
6791
6792                 if (!fid_is_sane(fid))
6793                         attr |= LUDA_UNKNOWN;
6794         } else {
6795                 attr &= ~LU_DIRENT_ATTRS_MASK;
6796                 if (!fid_is_sane(fid)) {
6797                         bool is_dotdot = false;
6798                         if (it->oie_dirent->oied_namelen == 2 &&
6799                             it->oie_dirent->oied_name[0] == '.' &&
6800                             it->oie_dirent->oied_name[1] == '.')
6801                                 is_dotdot = true;
6802                         /* If the parent is on remote MDT, and there
6803                          * is no FID-in-dirent, then we have to get
6804                          * the parent FID from the linkEA.  */
6805                         if (ino == osd_remote_parent_ino(dev) && is_dotdot) {
6806                                 rc = osd_get_pfid_from_linkea(env, obj, fid);
6807                         } else {
6808                                 if (is_dotdot == false &&
6809                                     OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
6810                                         RETURN(-ENOENT);
6811
6812                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
6813                         }
6814                 } else {
6815                         osd_id_gen(id, ino, OSD_OII_NOGEN);
6816                 }
6817         }
6818
6819         /* Pack the entry anyway, at least the offset is right. */
6820         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
6821                            it->oie_dirent->oied_name,
6822                            it->oie_dirent->oied_namelen,
6823                            it->oie_dirent->oied_type, attr);
6824
6825         if (rc < 0)
6826                 RETURN(rc);
6827
6828         if (osd_remote_fid(env, dev, fid))
6829                 RETURN(0);
6830
6831         if (likely(!(attr & (LUDA_IGNORE | LUDA_UNKNOWN)) && rc == 0))
6832                 osd_add_oi_cache(oti, dev, id, fid);
6833
6834         RETURN(rc > 0 ? 0 : rc);
6835 }
6836
6837 /**
6838  * Returns the record size size at current position.
6839  *
6840  * This function will return record(lu_dirent) size in bytes.
6841  *
6842  * \param[in] env       execution environment
6843  * \param[in] di        iterator's in memory structure
6844  * \param[in] attr      attribute of the entry, only requires LUDA_TYPE to
6845  *                      calculate the lu_dirent size.
6846  *
6847  * \retval      record size(in bytes & in memory) of the current lu_dirent
6848  *              entry.
6849  */
6850 static int osd_it_ea_rec_size(const struct lu_env *env, const struct dt_it *di,
6851                               __u32 attr)
6852 {
6853         struct osd_it_ea *it = (struct osd_it_ea *)di;
6854
6855         return lu_dirent_calc_size(it->oie_dirent->oied_namelen, attr);
6856 }
6857
6858 /**
6859  * Returns a cookie for current position of the iterator head, so that
6860  * user can use this cookie to load/start the iterator next time.
6861  *
6862  * \param di iterator's in memory structure
6863  *
6864  * \retval cookie for current position, on success
6865  */
6866 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
6867 {
6868         struct osd_it_ea *it = (struct osd_it_ea *)di;
6869
6870         return it->oie_dirent->oied_off;
6871 }
6872
6873 /**
6874  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
6875  * to load a directory entry at a time and stored it i inn,
6876  * in iterator's in-memory data structure.
6877  *
6878  * \param di struct osd_it_ea, iterator's in memory structure
6879  *
6880  * \retval +ve on success
6881  * \retval -ve on error
6882  */
6883 static int osd_it_ea_load(const struct lu_env *env,
6884                           const struct dt_it *di, __u64 hash)
6885 {
6886         struct osd_it_ea *it = (struct osd_it_ea *)di;
6887         int rc;
6888
6889         ENTRY;
6890         it->oie_file.f_pos = hash;
6891
6892         rc =  osd_ldiskfs_it_fill(env, di);
6893         if (rc > 0)
6894                 rc = -ENODATA;
6895
6896         if (rc == 0)
6897                 rc = +1;
6898
6899         RETURN(rc);
6900 }
6901
6902 /**
6903  * Index lookup function for interoperability mode (b11826).
6904  *
6905  * \param key,  key i.e. file name to be searched
6906  *
6907  * \retval +ve, on success
6908  * \retval -ve, on error
6909  */
6910 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
6911                                struct dt_rec *rec, const struct dt_key *key)
6912 {
6913         struct osd_object *obj = osd_dt_obj(dt);
6914         int rc = 0;
6915
6916         ENTRY;
6917
6918         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
6919         LINVRNT(osd_invariant(obj));
6920
6921         rc = osd_ea_lookup_rec(env, obj, rec, key);
6922         if (rc == 0)
6923                 rc = +1;
6924         RETURN(rc);
6925 }
6926
6927 /**
6928  * Index and Iterator operations for interoperability
6929  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
6930  */
6931 static const struct dt_index_operations osd_index_ea_ops = {
6932         .dio_lookup         = osd_index_ea_lookup,
6933         .dio_declare_insert = osd_index_declare_ea_insert,
6934         .dio_insert         = osd_index_ea_insert,
6935         .dio_declare_delete = osd_index_declare_ea_delete,
6936         .dio_delete         = osd_index_ea_delete,
6937         .dio_it     = {
6938                 .init     = osd_it_ea_init,
6939                 .fini     = osd_it_ea_fini,
6940                 .get      = osd_it_ea_get,
6941                 .put      = osd_it_ea_put,
6942                 .next     = osd_it_ea_next,
6943                 .key      = osd_it_ea_key,
6944                 .key_size = osd_it_ea_key_size,
6945                 .rec      = osd_it_ea_rec,
6946                 .rec_size = osd_it_ea_rec_size,
6947                 .store    = osd_it_ea_store,
6948                 .load     = osd_it_ea_load
6949         }
6950 };
6951
6952 static void *osd_key_init(const struct lu_context *ctx,
6953                           struct lu_context_key *key)
6954 {
6955         struct osd_thread_info *info;
6956
6957         OBD_ALLOC_PTR(info);
6958         if (info == NULL)
6959                 return ERR_PTR(-ENOMEM);
6960
6961         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
6962         if (info->oti_it_ea_buf == NULL)
6963                 goto out_free_info;
6964
6965         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
6966
6967         info->oti_hlock = ldiskfs_htree_lock_alloc();
6968         if (info->oti_hlock == NULL)
6969                 goto out_free_ea;
6970
6971         return info;
6972
6973  out_free_ea:
6974         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
6975  out_free_info:
6976         OBD_FREE_PTR(info);
6977         return ERR_PTR(-ENOMEM);
6978 }
6979
6980 static void osd_key_fini(const struct lu_context *ctx,
6981                          struct lu_context_key *key, void* data)
6982 {
6983         struct osd_thread_info *info = data;
6984         struct ldiskfs_inode_info *lli = LDISKFS_I(info->oti_inode);
6985         struct osd_idmap_cache  *idc = info->oti_ins_cache;
6986
6987         if (info->oti_inode != NULL)
6988                 OBD_FREE_PTR(lli);
6989         if (info->oti_hlock != NULL)
6990                 ldiskfs_htree_lock_free(info->oti_hlock);
6991         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
6992         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
6993         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
6994         lu_buf_free(&info->oti_big_buf);
6995         if (idc != NULL) {
6996                 LASSERT(info->oti_ins_cache_size > 0);
6997                 OBD_FREE(idc, sizeof(*idc) * info->oti_ins_cache_size);
6998                 info->oti_ins_cache = NULL;
6999                 info->oti_ins_cache_size = 0;
7000         }
7001         OBD_FREE_PTR(info);
7002 }
7003
7004 static void osd_key_exit(const struct lu_context *ctx,
7005                          struct lu_context_key *key, void *data)
7006 {
7007         struct osd_thread_info *info = data;
7008
7009         LASSERT(info->oti_r_locks == 0);
7010         LASSERT(info->oti_w_locks == 0);
7011         LASSERT(info->oti_txns    == 0);
7012 }
7013
7014 /* type constructor/destructor: osd_type_init, osd_type_fini */
7015 LU_TYPE_INIT_FINI(osd, &osd_key);
7016
7017 struct lu_context_key osd_key = {
7018         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
7019         .lct_init = osd_key_init,
7020         .lct_fini = osd_key_fini,
7021         .lct_exit = osd_key_exit
7022 };
7023
7024
7025 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
7026                            const char *name, struct lu_device *next)
7027 {
7028         struct osd_device *osd = osd_dev(d);
7029
7030         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
7031             >= sizeof(osd->od_svname))
7032                 return -E2BIG;
7033         return osd_procfs_init(osd, name);
7034 }
7035
7036 static int osd_fid_init(const struct lu_env *env, struct osd_device *osd)
7037 {
7038         struct seq_server_site  *ss = osd_seq_site(osd);
7039         int                     rc;
7040         ENTRY;
7041
7042         if (osd->od_is_ost || osd->od_cl_seq != NULL)
7043                 RETURN(0);
7044
7045         if (unlikely(ss == NULL))
7046                 RETURN(-ENODEV);
7047
7048         OBD_ALLOC_PTR(osd->od_cl_seq);
7049         if (osd->od_cl_seq == NULL)
7050                 RETURN(-ENOMEM);
7051
7052         rc = seq_client_init(osd->od_cl_seq, NULL, LUSTRE_SEQ_METADATA,
7053                              osd->od_svname, ss->ss_server_seq);
7054         if (rc != 0) {
7055                 OBD_FREE_PTR(osd->od_cl_seq);
7056                 osd->od_cl_seq = NULL;
7057                 RETURN(rc);
7058         }
7059
7060         if (ss->ss_node_id == 0) {
7061                 /* If the OSD on the sequence controller(MDT0), then allocate
7062                  * sequence here, otherwise allocate sequence after connected
7063                  * to MDT0 (see mdt_register_lwp_callback()). */
7064                 rc = seq_server_alloc_meta(osd->od_cl_seq->lcs_srv,
7065                                    &osd->od_cl_seq->lcs_space, env);
7066         }
7067
7068         RETURN(rc);
7069 }
7070
7071 static void osd_fid_fini(const struct lu_env *env, struct osd_device *osd)
7072 {
7073         if (osd->od_cl_seq == NULL)
7074                 return;
7075
7076         seq_client_fini(osd->od_cl_seq);
7077         OBD_FREE_PTR(osd->od_cl_seq);
7078         osd->od_cl_seq = NULL;
7079 }
7080
7081 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
7082 {
7083         ENTRY;
7084
7085         /* shutdown quota slave instance associated with the device */
7086         if (o->od_quota_slave != NULL) {
7087                 struct qsd_instance *qsd = o->od_quota_slave;
7088
7089                 o->od_quota_slave = NULL;
7090                 qsd_fini(env, qsd);
7091         }
7092
7093         osd_fid_fini(env, o);
7094         osd_scrub_cleanup(env, o);
7095
7096         RETURN(0);
7097 }
7098
7099 static void osd_umount(const struct lu_env *env, struct osd_device *o)
7100 {
7101         ENTRY;
7102
7103         if (o->od_mnt != NULL) {
7104                 shrink_dcache_sb(osd_sb(o));
7105                 osd_sync(env, &o->od_dt_dev);
7106
7107                 mntput(o->od_mnt);
7108                 o->od_mnt = NULL;
7109         }
7110
7111         EXIT;
7112 }
7113
7114 static int osd_mount(const struct lu_env *env,
7115                      struct osd_device *o, struct lustre_cfg *cfg)
7116 {
7117         const char              *name  = lustre_cfg_string(cfg, 0);
7118         const char              *dev  = lustre_cfg_string(cfg, 1);
7119         const char              *opts;
7120         unsigned long            page, s_flags, lmd_flags = 0;
7121         struct page             *__page;
7122         struct file_system_type *type;
7123         char                    *options = NULL;
7124         char                    *str;
7125         struct osd_thread_info  *info = osd_oti_get(env);
7126         struct lu_fid           *fid = &info->oti_fid;
7127         struct inode            *inode;
7128         int                      rc = 0, force_over_512tb = 0;
7129         ENTRY;
7130
7131         if (o->od_mnt != NULL)
7132                 RETURN(0);
7133
7134         if (strlen(dev) >= sizeof(o->od_mntdev))
7135                 RETURN(-E2BIG);
7136         strcpy(o->od_mntdev, dev);
7137
7138         str = lustre_cfg_string(cfg, 2);
7139         s_flags = simple_strtoul(str, NULL, 0);
7140         str = strstr(str, ":");
7141         if (str)
7142                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
7143         opts = lustre_cfg_string(cfg, 3);
7144 #ifdef __BIG_ENDIAN
7145         if (opts == NULL || strstr(opts, "bigendian_extents") == NULL) {
7146                 CERROR("%s: device %s extents feature is not guaranteed to "
7147                        "work on big-endian systems. Use \"bigendian_extents\" "
7148                        "mount option to override.\n", name, dev);
7149                 RETURN(-EINVAL);
7150         }
7151 #endif
7152 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7153         if (opts != NULL && strstr(opts, "force_over_128tb") != NULL) {
7154                 CWARN("force_over_128tb option is deprecated. "
7155                       "Filesystems less than 512TB can be created without any "
7156                       "force options. Use force_over_512tb option for "
7157                       "filesystems greater than 512TB.\n");
7158         }
7159 #endif
7160 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 1, 53, 0)
7161         if (opts != NULL && strstr(opts, "force_over_256tb") != NULL) {
7162                 CWARN("force_over_256tb option is deprecated. "
7163                       "Filesystems less than 512TB can be created without any "
7164                       "force options. Use force_over_512tb option for "
7165                       "filesystems greater than 512TB.\n");
7166         }
7167 #endif
7168
7169         if (opts != NULL && strstr(opts, "force_over_512tb") != NULL)
7170                 force_over_512tb = 1;
7171
7172         __page = alloc_page(GFP_KERNEL);
7173         if (__page == NULL)
7174                 GOTO(out, rc = -ENOMEM);
7175         page = (unsigned long)page_address(__page);
7176         options = (char *)page;
7177         *options = '\0';
7178         if (opts != NULL) {
7179                 /* strip out the options for back compatiblity */
7180                 static char *sout[] = {
7181                         "mballoc",
7182                         "iopen",
7183                         "noiopen",
7184                         "iopen_nopriv",
7185                         "extents",
7186                         "noextents",
7187                         /* strip out option we processed in osd */
7188                         "bigendian_extents",
7189                         "force_over_128tb",
7190                         "force_over_256tb",
7191                         "force_over_512tb",
7192                         NULL
7193                 };
7194                 strcat(options, opts);
7195                 for (rc = 0, str = options; sout[rc]; ) {
7196                         char *op = strstr(str, sout[rc]);
7197                         if (op == NULL) {
7198                                 rc++;
7199                                 str = options;
7200                                 continue;
7201                         }
7202                         if (op == options || *(op - 1) == ',') {
7203                                 str = op + strlen(sout[rc]);
7204                                 if (*str == ',' || *str == '\0') {
7205                                         *str == ',' ? str++ : str;
7206                                         memmove(op, str, strlen(str) + 1);
7207                                 }
7208                         }
7209                         for (str = op; *str != ',' && *str != '\0'; str++)
7210                                 ;
7211                 }
7212         } else {
7213                 strncat(options, "user_xattr,acl", 14);
7214         }
7215
7216         /* Glom up mount options */
7217         if (*options != '\0')
7218                 strcat(options, ",");
7219         strlcat(options, "no_mbcache,nodelalloc", PAGE_SIZE);
7220
7221         type = get_fs_type("ldiskfs");
7222         if (!type) {
7223                 CERROR("%s: cannot find ldiskfs module\n", name);
7224                 GOTO(out, rc = -ENODEV);
7225         }
7226
7227         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
7228         module_put(type->owner);
7229
7230         if (IS_ERR(o->od_mnt)) {
7231                 rc = PTR_ERR(o->od_mnt);
7232                 o->od_mnt = NULL;
7233                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
7234                 GOTO(out, rc);
7235         }
7236
7237         if (ldiskfs_blocks_count(LDISKFS_SB(osd_sb(o))->s_es) <<
7238                                  osd_sb(o)->s_blocksize_bits > 512ULL << 40 &&
7239                                  force_over_512tb == 0) {
7240                 CERROR("%s: device %s LDISKFS does not support filesystems "
7241                        "greater than 512TB and can cause data corruption. "
7242                        "Use \"force_over_512tb\" mount option to override.\n",
7243                        name, dev);
7244                 GOTO(out_mnt, rc = -EINVAL);
7245         }
7246
7247         if (lmd_flags & LMD_FLG_DEV_RDONLY) {
7248                 if (priv_dev_set_rdonly) {
7249                         priv_dev_set_rdonly(osd_sb(o)->s_bdev);
7250                         o->od_dt_dev.dd_rdonly = 1;
7251                         LCONSOLE_WARN("%s: set dev_rdonly on this device\n",
7252                                       name);
7253                 } else {
7254                         LCONSOLE_WARN("%s: not support dev_rdonly on this device",
7255                                       name);
7256
7257                         GOTO(out_mnt, rc = -EOPNOTSUPP);
7258                 }
7259         } else if (priv_dev_check_rdonly &&
7260                    priv_dev_check_rdonly(osd_sb(o)->s_bdev)) {
7261                 CERROR("%s: underlying device %s is marked as "
7262                        "read-only. Setup failed\n", name, dev);
7263
7264                 GOTO(out_mnt, rc = -EROFS);
7265         }
7266
7267         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
7268                                         LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
7269                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
7270                 GOTO(out_mnt, rc = -EINVAL);
7271         }
7272
7273 #ifdef LDISKFS_MOUNT_DIRDATA
7274         if (LDISKFS_HAS_INCOMPAT_FEATURE(o->od_mnt->mnt_sb,
7275                                          LDISKFS_FEATURE_INCOMPAT_DIRDATA))
7276                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
7277         else if (strstr(name, "MDT")) /* don't complain for MGT or OSTs */
7278                 CWARN("%s: device %s was upgraded from Lustre-1.x without "
7279                       "enabling the dirdata feature. If you do not want to "
7280                       "downgrade to Lustre-1.x again, you can enable it via "
7281                       "'tune2fs -O dirdata device'\n", name, dev);
7282 #endif
7283         inode = osd_sb(o)->s_root->d_inode;
7284         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
7285         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
7286         if (rc != 0) {
7287                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
7288                 GOTO(out_mnt, rc);
7289         }
7290
7291         if (lmd_flags & LMD_FLG_NOSCRUB)
7292                 o->od_auto_scrub_interval = AS_NEVER;
7293
7294         GOTO(out, rc = 0);
7295
7296 out_mnt:
7297         mntput(o->od_mnt);
7298         o->od_mnt = NULL;
7299
7300 out:
7301         if (__page)
7302                 __free_page(__page);
7303
7304         return rc;
7305 }
7306
7307 static struct lu_device *osd_device_fini(const struct lu_env *env,
7308                                          struct lu_device *d)
7309 {
7310         struct osd_device *o = osd_dev(d);
7311         ENTRY;
7312
7313         osd_index_backup(env, o, false);
7314         osd_shutdown(env, o);
7315         osd_procfs_fini(o);
7316         osd_obj_map_fini(o);
7317         osd_umount(env, o);
7318
7319         RETURN(NULL);
7320 }
7321
7322 static int osd_device_init0(const struct lu_env *env,
7323                             struct osd_device *o,
7324                             struct lustre_cfg *cfg)
7325 {
7326         struct lu_device        *l = osd2lu_dev(o);
7327         struct osd_thread_info *info;
7328         int                     rc;
7329         int                     cplen = 0;
7330
7331         /* if the module was re-loaded, env can loose its keys */
7332         rc = lu_env_refill((struct lu_env *) env);
7333         if (rc)
7334                 GOTO(out, rc);
7335         info = osd_oti_get(env);
7336         LASSERT(info);
7337
7338         l->ld_ops = &osd_lu_ops;
7339         o->od_dt_dev.dd_ops = &osd_dt_ops;
7340
7341         spin_lock_init(&o->od_osfs_lock);
7342         mutex_init(&o->od_otable_mutex);
7343         INIT_LIST_HEAD(&o->od_orphan_list);
7344         INIT_LIST_HEAD(&o->od_index_backup_list);
7345         INIT_LIST_HEAD(&o->od_index_restore_list);
7346         spin_lock_init(&o->od_lock);
7347         o->od_index_backup_policy = LIBP_NONE;
7348
7349         o->od_read_cache = 1;
7350         o->od_writethrough_cache = 1;
7351         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
7352         o->od_auto_scrub_interval = AS_DEFAULT;
7353
7354         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
7355                         sizeof(o->od_svname));
7356         if (cplen >= sizeof(o->od_svname)) {
7357                 rc = -E2BIG;
7358                 GOTO(out, rc);
7359         }
7360
7361         o->od_index_backup_stop = 0;
7362         o->od_index = -1; /* -1 means index is invalid */
7363         rc = server_name2index(o->od_svname, &o->od_index, NULL);
7364         if (rc == LDD_F_SV_TYPE_OST)
7365                 o->od_is_ost = 1;
7366
7367         o->od_full_scrub_ratio = OFSR_DEFAULT;
7368         o->od_full_scrub_threshold_rate = FULL_SCRUB_THRESHOLD_RATE_DEFAULT;
7369         rc = osd_mount(env, o, cfg);
7370         if (rc != 0)
7371                 GOTO(out, rc);
7372
7373         rc = osd_obj_map_init(env, o);
7374         if (rc != 0)
7375                 GOTO(out_mnt, rc);
7376
7377         rc = lu_site_init(&o->od_site, l);
7378         if (rc != 0)
7379                 GOTO(out_compat, rc);
7380         o->od_site.ls_bottom_dev = l;
7381
7382         rc = lu_site_init_finish(&o->od_site);
7383         if (rc != 0)
7384                 GOTO(out_site, rc);
7385
7386         INIT_LIST_HEAD(&o->od_ios_list);
7387         /* setup scrub, including OI files initialization */
7388         o->od_in_init = 1;
7389         rc = osd_scrub_setup(env, o);
7390         o->od_in_init = 0;
7391         if (rc < 0)
7392                 GOTO(out_site, rc);
7393
7394         rc = osd_procfs_init(o, o->od_svname);
7395         if (rc != 0) {
7396                 CERROR("%s: can't initialize procfs: rc = %d\n",
7397                        o->od_svname, rc);
7398                 GOTO(out_scrub, rc);
7399         }
7400
7401         LASSERT(l->ld_site->ls_linkage.next != NULL);
7402         LASSERT(l->ld_site->ls_linkage.prev != NULL);
7403
7404         /* initialize quota slave instance */
7405         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
7406                                      o->od_proc_entry);
7407         if (IS_ERR(o->od_quota_slave)) {
7408                 rc = PTR_ERR(o->od_quota_slave);
7409                 o->od_quota_slave = NULL;
7410                 GOTO(out_procfs, rc);
7411         }
7412
7413         RETURN(0);
7414
7415 out_procfs:
7416         osd_procfs_fini(o);
7417 out_scrub:
7418         osd_scrub_cleanup(env, o);
7419 out_site:
7420         lu_site_fini(&o->od_site);
7421 out_compat:
7422         osd_obj_map_fini(o);
7423 out_mnt:
7424         osd_umount(env, o);
7425 out:
7426         return rc;
7427 }
7428
7429 static struct lu_device *osd_device_alloc(const struct lu_env *env,
7430                                           struct lu_device_type *t,
7431                                           struct lustre_cfg *cfg)
7432 {
7433         struct osd_device *o;
7434         int                rc;
7435
7436         OBD_ALLOC_PTR(o);
7437         if (o == NULL)
7438                 return ERR_PTR(-ENOMEM);
7439
7440         rc = dt_device_init(&o->od_dt_dev, t);
7441         if (rc == 0) {
7442                 /* Because the ctx might be revived in dt_device_init,
7443                  * refill the env here */
7444                 lu_env_refill((struct lu_env *)env);
7445                 rc = osd_device_init0(env, o, cfg);
7446                 if (rc)
7447                         dt_device_fini(&o->od_dt_dev);
7448         }
7449
7450         if (unlikely(rc != 0))
7451                 OBD_FREE_PTR(o);
7452
7453         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
7454 }
7455
7456 static struct lu_device *osd_device_free(const struct lu_env *env,
7457                                          struct lu_device *d)
7458 {
7459         struct osd_device *o = osd_dev(d);
7460         ENTRY;
7461
7462         /* XXX: make osd top device in order to release reference */
7463         d->ld_site->ls_top_dev = d;
7464         lu_site_purge(env, d->ld_site, -1);
7465         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
7466                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
7467                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
7468         }
7469         lu_site_fini(&o->od_site);
7470         dt_device_fini(&o->od_dt_dev);
7471         OBD_FREE_PTR(o);
7472         RETURN(NULL);
7473 }
7474
7475 static int osd_process_config(const struct lu_env *env,
7476                               struct lu_device *d, struct lustre_cfg *cfg)
7477 {
7478         struct osd_device               *o = osd_dev(d);
7479         int                             rc;
7480         ENTRY;
7481
7482         switch (cfg->lcfg_command) {
7483         case LCFG_SETUP:
7484                 rc = osd_mount(env, o, cfg);
7485                 break;
7486         case LCFG_CLEANUP:
7487                 /* For the case LCFG_PRE_CLEANUP is not called in advance,
7488                  * that may happend if hit failure during mount process. */
7489                 osd_index_backup(env, o, false);
7490                 lu_dev_del_linkage(d->ld_site, d);
7491                 rc = osd_shutdown(env, o);
7492                 break;
7493         case LCFG_PARAM:
7494                 LASSERT(&o->od_dt_dev);
7495                 rc = class_process_proc_param(PARAM_OSD, lprocfs_osd_obd_vars,
7496                                               cfg, &o->od_dt_dev);
7497                 if (rc > 0 || rc == -ENOSYS) {
7498                         rc = class_process_proc_param(PARAM_OST,
7499                                                       lprocfs_osd_obd_vars,
7500                                                       cfg, &o->od_dt_dev);
7501                         if (rc > 0)
7502                                 rc = 0;
7503                 }
7504                 break;
7505         case LCFG_PRE_CLEANUP:
7506                 osd_scrub_stop(o);
7507                 osd_index_backup(env, o,
7508                                  o->od_index_backup_policy != LIBP_NONE);
7509                 rc = 0;
7510                 break;
7511         default:
7512                 rc = -ENOSYS;
7513         }
7514
7515         RETURN(rc);
7516 }
7517
7518 static int osd_recovery_complete(const struct lu_env *env,
7519                                  struct lu_device *d)
7520 {
7521         struct osd_device       *osd = osd_dev(d);
7522         int                      rc = 0;
7523         ENTRY;
7524
7525         if (osd->od_quota_slave == NULL)
7526                 RETURN(0);
7527
7528         /* start qsd instance on recovery completion, this notifies the quota
7529          * slave code that we are about to process new requests now */
7530         rc = qsd_start(env, osd->od_quota_slave);
7531         RETURN(rc);
7532 }
7533
7534 /*
7535  * we use exports to track all osd users
7536  */
7537 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
7538                            struct obd_device *obd, struct obd_uuid *cluuid,
7539                            struct obd_connect_data *data, void *localdata)
7540 {
7541         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
7542         struct lustre_handle  conn;
7543         int                   rc;
7544         ENTRY;
7545
7546         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
7547
7548         rc = class_connect(&conn, obd, cluuid);
7549         if (rc)
7550                 RETURN(rc);
7551
7552         *exp = class_conn2export(&conn);
7553
7554         spin_lock(&osd->od_osfs_lock);
7555         osd->od_connects++;
7556         spin_unlock(&osd->od_osfs_lock);
7557
7558         RETURN(0);
7559 }
7560
7561 /*
7562  * once last export (we don't count self-export) disappeared
7563  * osd can be released
7564  */
7565 static int osd_obd_disconnect(struct obd_export *exp)
7566 {
7567         struct obd_device *obd = exp->exp_obd;
7568         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
7569         int                rc, release = 0;
7570         ENTRY;
7571
7572         /* Only disconnect the underlying layers on the final disconnect. */
7573         spin_lock(&osd->od_osfs_lock);
7574         osd->od_connects--;
7575         if (osd->od_connects == 0)
7576                 release = 1;
7577         spin_unlock(&osd->od_osfs_lock);
7578
7579         rc = class_disconnect(exp); /* bz 9811 */
7580
7581         if (rc == 0 && release)
7582                 class_manual_cleanup(obd);
7583         RETURN(rc);
7584 }
7585
7586 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
7587                        struct lu_device *dev)
7588 {
7589         struct osd_device       *osd    = osd_dev(dev);
7590         struct lr_server_data   *lsd    =
7591                         &osd->od_dt_dev.dd_lu_dev.ld_site->ls_tgt->lut_lsd;
7592         int                      result = 0;
7593         ENTRY;
7594
7595         if (osd->od_quota_slave != NULL) {
7596                 /* set up quota slave objects */
7597                 result = qsd_prepare(env, osd->od_quota_slave);
7598                 if (result != 0)
7599                         RETURN(result);
7600         }
7601
7602         if (lsd->lsd_feature_incompat & OBD_COMPAT_OST) {
7603 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 52, 0)
7604                 if (lsd->lsd_feature_rocompat & OBD_ROCOMPAT_IDX_IN_IDIF) {
7605                         osd->od_index_in_idif = 1;
7606                 } else {
7607                         osd->od_index_in_idif = 0;
7608                         result = osd_register_proc_index_in_idif(osd);
7609                         if (result != 0)
7610                                 RETURN(result);
7611                 }
7612 #else
7613                 osd->od_index_in_idif = 1;
7614 #endif
7615         }
7616
7617         result = osd_fid_init(env, osd);
7618
7619         RETURN(result);
7620 }
7621
7622 static int osd_fid_alloc(const struct lu_env *env, struct obd_export *exp,
7623                          struct lu_fid *fid, struct md_op_data *op_data)
7624 {
7625         struct osd_device *osd = osd_dev(exp->exp_obd->obd_lu_dev);
7626
7627         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
7628 }
7629
7630 static const struct lu_object_operations osd_lu_obj_ops = {
7631         .loo_object_init      = osd_object_init,
7632         .loo_object_delete    = osd_object_delete,
7633         .loo_object_release   = osd_object_release,
7634         .loo_object_free      = osd_object_free,
7635         .loo_object_print     = osd_object_print,
7636         .loo_object_invariant = osd_object_invariant
7637 };
7638
7639 const struct lu_device_operations osd_lu_ops = {
7640         .ldo_object_alloc      = osd_object_alloc,
7641         .ldo_process_config    = osd_process_config,
7642         .ldo_recovery_complete = osd_recovery_complete,
7643         .ldo_prepare           = osd_prepare,
7644 };
7645
7646 static const struct lu_device_type_operations osd_device_type_ops = {
7647         .ldto_init = osd_type_init,
7648         .ldto_fini = osd_type_fini,
7649
7650         .ldto_start = osd_type_start,
7651         .ldto_stop  = osd_type_stop,
7652
7653         .ldto_device_alloc = osd_device_alloc,
7654         .ldto_device_free  = osd_device_free,
7655
7656         .ldto_device_init    = osd_device_init,
7657         .ldto_device_fini    = osd_device_fini
7658 };
7659
7660 static struct lu_device_type osd_device_type = {
7661         .ldt_tags     = LU_DEVICE_DT,
7662         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
7663         .ldt_ops      = &osd_device_type_ops,
7664         .ldt_ctx_tags = LCT_LOCAL,
7665 };
7666
7667 static int osd_health_check(const struct lu_env *env, struct obd_device *obd)
7668 {
7669         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
7670         struct super_block *sb = osd_sb(osd);
7671
7672         return (osd->od_mnt == NULL || sb->s_flags & MS_RDONLY);
7673 }
7674
7675 /*
7676  * lprocfs legacy support.
7677  */
7678 static struct obd_ops osd_obd_device_ops = {
7679         .o_owner = THIS_MODULE,
7680         .o_connect      = osd_obd_connect,
7681         .o_disconnect   = osd_obd_disconnect,
7682         .o_fid_alloc    = osd_fid_alloc,
7683         .o_health_check = osd_health_check,
7684 };
7685
7686 static int __init osd_init(void)
7687 {
7688         int rc;
7689
7690         CLASSERT(BH_DXLock < sizeof(((struct buffer_head *)0)->b_state) * 8);
7691 #if !defined(CONFIG_DEBUG_MUTEXES) && !defined(CONFIG_DEBUG_SPINLOCK)
7692         /* please, try to keep osd_thread_info smaller than a page */
7693         CLASSERT(sizeof(struct osd_thread_info) <= PAGE_SIZE);
7694 #endif
7695
7696         osd_oi_mod_init();
7697
7698         rc = lu_kmem_init(ldiskfs_caches);
7699         if (rc)
7700                 return rc;
7701
7702 #ifdef CONFIG_KALLSYMS
7703         priv_dev_set_rdonly = (void *)kallsyms_lookup_name("dev_set_rdonly");
7704         priv_dev_check_rdonly = (void *)kallsyms_lookup_name("dev_check_rdonly");
7705         /* Clear readonly is unused at this time */
7706         /*priv_dev_clear_rdonly = (void *)kallsyms_lookup_name("dev_clear_rdonly");*/
7707 #endif
7708
7709         rc = class_register_type(&osd_obd_device_ops, NULL, true,
7710                                  lprocfs_osd_module_vars,
7711                                  LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
7712         if (rc)
7713                 lu_kmem_fini(ldiskfs_caches);
7714         return rc;
7715 }
7716
7717 static void __exit osd_exit(void)
7718 {
7719         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
7720         lu_kmem_fini(ldiskfs_caches);
7721 }
7722
7723 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
7724 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
7725 MODULE_VERSION(LUSTRE_VERSION_STRING);
7726 MODULE_LICENSE("GPL");
7727
7728 module_init(osd_init);
7729 module_exit(osd_exit);