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