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