Whamcloud - gitweb
118bec0af47a9ec5d57f02b076021bb940e9fa3c
[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)
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 (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 (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 (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 (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;
2570         bspace <<= obj->oo_inode->i_sb->s_blocksize_bits;
2571         bspace   = toqb(bspace);
2572
2573         /* Changing ownership is always preformed by super user, it should not
2574          * fail with EDQUOT.
2575          *
2576          * We still need to call the osd_declare_qid() to calculate the journal
2577          * credits for updating quota accounting files and to trigger quota
2578          * space adjustment once the operation is completed.*/
2579         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
2580                 /* USERQUOTA */
2581                 uid = i_uid_read(obj->oo_inode);
2582                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
2583                 rc = osd_declare_attr_qid(env, obj, oh, bspace, uid,
2584                                           attr->la_uid, enforce, USRQUOTA);
2585                 if (rc)
2586                         RETURN(rc);
2587
2588                 gid = i_gid_read(obj->oo_inode);
2589                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
2590                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2591                                           i_gid_read(obj->oo_inode),
2592                                           attr->la_gid, enforce, GRPQUOTA);
2593                 if (rc)
2594                         RETURN(rc);
2595
2596         }
2597 #ifdef HAVE_PROJECT_QUOTA
2598         if (attr->la_valid & LA_PROJID) {
2599                 __u32 projid = i_projid_read(obj->oo_inode);
2600                 enforce = (attr->la_valid & LA_PROJID) &&
2601                                         (attr->la_projid != projid);
2602                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2603                                           (qid_t)projid, (qid_t)attr->la_projid,
2604                                           enforce, PRJQUOTA);
2605                 if (rc)
2606                         RETURN(rc);
2607         }
2608 #endif
2609         RETURN(rc);
2610 }
2611
2612 static int osd_inode_setattr(const struct lu_env *env,
2613                              struct inode *inode, const struct lu_attr *attr)
2614 {
2615         __u64 bits = attr->la_valid;
2616
2617         /* Only allow set size for regular file */
2618         if (!S_ISREG(inode->i_mode))
2619                 bits &= ~(LA_SIZE | LA_BLOCKS);
2620
2621         if (bits == 0)
2622                 return 0;
2623
2624         if (bits & LA_ATIME)
2625                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
2626         if (bits & LA_CTIME)
2627                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
2628         if (bits & LA_MTIME)
2629                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
2630         if (bits & LA_SIZE) {
2631                 spin_lock(&inode->i_lock);
2632                 LDISKFS_I(inode)->i_disksize = attr->la_size;
2633                 i_size_write(inode, attr->la_size);
2634                 spin_unlock(&inode->i_lock);
2635         }
2636
2637         /* OSD should not change "i_blocks" which is used by quota.
2638          * "i_blocks" should be changed by ldiskfs only. */
2639         if (bits & LA_MODE)
2640                 inode->i_mode = (inode->i_mode & S_IFMT) |
2641                                 (attr->la_mode & ~S_IFMT);
2642         if (bits & LA_UID)
2643                 i_uid_write(inode, attr->la_uid);
2644         if (bits & LA_GID)
2645                 i_gid_write(inode, attr->la_gid);
2646         if (bits & LA_PROJID)
2647                 i_projid_write(inode, attr->la_projid);
2648         if (bits & LA_NLINK)
2649                 set_nlink(inode, attr->la_nlink);
2650         if (bits & LA_RDEV)
2651                 inode->i_rdev = attr->la_rdev;
2652
2653         if (bits & LA_FLAGS) {
2654                 /* always keep S_NOCMTIME */
2655                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
2656                                  S_NOCMTIME;
2657                 /*
2658                  * Ext4 did not transfer inherit flags from
2659                  * @inode->i_flags to raw inode i_flags when writing
2660                  * flags, we do it explictly here.
2661                  */
2662                 if (attr->la_flags & LUSTRE_PROJINHERIT_FL)
2663                         LDISKFS_I(inode)->i_flags |= LUSTRE_PROJINHERIT_FL;
2664                 else
2665                         LDISKFS_I(inode)->i_flags &= ~LUSTRE_PROJINHERIT_FL;
2666         }
2667         return 0;
2668 }
2669
2670 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
2671 {
2672         int rc;
2673
2674         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
2675             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
2676                 struct iattr    iattr;
2677
2678                 ll_vfs_dq_init(inode);
2679                 iattr.ia_valid = 0;
2680                 if (attr->la_valid & LA_UID)
2681                         iattr.ia_valid |= ATTR_UID;
2682                 if (attr->la_valid & LA_GID)
2683                         iattr.ia_valid |= ATTR_GID;
2684                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
2685                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
2686
2687                 rc = ll_vfs_dq_transfer(inode, &iattr);
2688                 if (rc) {
2689                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
2690                                "enforcement enabled on the ldiskfs "
2691                                "filesystem?\n", inode->i_sb->s_id, rc);
2692                         return rc;
2693                 }
2694         }
2695
2696         /* Handle project id transfer here properly */
2697         if (attr->la_valid & LA_PROJID &&
2698             attr->la_projid != i_projid_read(inode)) {
2699 #ifdef HAVE_PROJECT_QUOTA
2700                 rc = ldiskfs_transfer_project(inode, attr->la_projid);
2701 #else
2702                 rc = -ENOTSUPP;
2703 #endif
2704                 if (rc) {
2705                         CERROR("%s: quota transfer failed: rc = %d. Is project "
2706                                "enforcement enabled on the ldiskfs "
2707                                "filesystem?\n", inode->i_sb->s_id, rc);
2708                         return rc;
2709                 }
2710         }
2711         return 0;
2712 }
2713
2714 static int osd_attr_set(const struct lu_env *env,
2715                         struct dt_object *dt,
2716                         const struct lu_attr *attr,
2717                         struct thandle *handle)
2718 {
2719         struct osd_object *obj = osd_dt_obj(dt);
2720         struct inode      *inode;
2721         int rc;
2722
2723         if (!dt_object_exists(dt))
2724                 return -ENOENT;
2725
2726         LASSERT(handle != NULL);
2727         LASSERT(!dt_object_remote(dt));
2728         LASSERT(osd_invariant(obj));
2729
2730         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
2731
2732         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING) &&
2733             !osd_obj2dev(obj)->od_is_ost) {
2734                 struct osd_thread_info  *oti  = osd_oti_get(env);
2735                 const struct lu_fid     *fid0 = lu_object_fid(&dt->do_lu);
2736                 struct lu_fid           *fid1 = &oti->oti_fid;
2737                 struct osd_inode_id     *id   = &oti->oti_id;
2738                 struct iam_path_descr   *ipd;
2739                 struct iam_container    *bag;
2740                 struct osd_thandle      *oh;
2741                 int                      rc;
2742
2743                 fid_cpu_to_be(fid1, fid0);
2744                 memset(id, 1, sizeof(*id));
2745                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
2746                                   fid0)->oi_dir.od_container;
2747                 ipd = osd_idx_ipd_get(env, bag);
2748                 if (unlikely(ipd == NULL))
2749                         RETURN(-ENOMEM);
2750
2751                 oh = container_of0(handle, struct osd_thandle, ot_super);
2752                 rc = iam_update(oh->ot_handle, bag, (const struct iam_key *)fid1,
2753                                 (const struct iam_rec *)id, ipd);
2754                 osd_ipd_put(env, bag, ipd);
2755                 return(rc > 0 ? 0 : rc);
2756         }
2757
2758         inode = obj->oo_inode;
2759
2760         rc = osd_quota_transfer(inode, attr);
2761         if (rc)
2762                 return rc;
2763
2764         spin_lock(&obj->oo_guard);
2765         rc = osd_inode_setattr(env, inode, attr);
2766         spin_unlock(&obj->oo_guard);
2767         if (rc != 0)
2768                 GOTO(out, rc);
2769
2770         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2771
2772         if (!(attr->la_valid & LA_FLAGS))
2773                 GOTO(out, rc);
2774
2775         /* Let's check if there are extra flags need to be set into LMA */
2776         if (attr->la_flags & LUSTRE_LMA_FL_MASKS) {
2777                 struct osd_thread_info *info = osd_oti_get(env);
2778                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
2779
2780                 LASSERT(!obj->oo_pfid_in_lma);
2781
2782                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
2783                                  &info->oti_ost_attrs);
2784                 if (rc)
2785                         GOTO(out, rc);
2786
2787                 lma->lma_incompat |=
2788                         lustre_to_lma_flags(attr->la_flags);
2789                 lustre_lma_swab(lma);
2790                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA,
2791                                      lma, sizeof(*lma), XATTR_REPLACE);
2792                 if (rc != 0) {
2793                         struct osd_device *osd = osd_obj2dev(obj);
2794
2795                         CWARN("%s: set "DFID" lma flags %u failed: rc = %d\n",
2796                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
2797                               lma->lma_incompat, rc);
2798                 } else {
2799                         obj->oo_lma_flags =
2800                                 attr->la_flags & LUSTRE_LMA_FL_MASKS;
2801                 }
2802                 osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
2803         }
2804 out:
2805         osd_trans_exec_check(env, handle, OSD_OT_ATTR_SET);
2806
2807         return rc;
2808 }
2809
2810 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
2811                                            struct osd_object *obj,
2812                                            const char *name, const int namelen)
2813 {
2814         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
2815 }
2816
2817 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
2818                       umode_t mode, struct dt_allocation_hint *hint,
2819                       struct thandle *th)
2820 {
2821         int result;
2822         struct osd_device  *osd = osd_obj2dev(obj);
2823         struct osd_thandle *oth;
2824         struct dt_object   *parent = NULL;
2825         struct inode       *inode;
2826
2827         LINVRNT(osd_invariant(obj));
2828         LASSERT(obj->oo_inode == NULL);
2829         LASSERT(obj->oo_hl_head == NULL);
2830
2831         if (S_ISDIR(mode) && ldiskfs_pdo) {
2832                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
2833                 if (obj->oo_hl_head == NULL)
2834                         return -ENOMEM;
2835         }
2836
2837         oth = container_of(th, struct osd_thandle, ot_super);
2838         LASSERT(oth->ot_handle->h_transaction != NULL);
2839
2840         if (hint != NULL && hint->dah_parent != NULL &&
2841             !dt_object_remote(hint->dah_parent))
2842                 parent = hint->dah_parent;
2843
2844         inode = ldiskfs_create_inode(oth->ot_handle,
2845                                      parent ? osd_dt_obj(parent)->oo_inode :
2846                                               osd_sb(osd)->s_root->d_inode,
2847                                      mode);
2848         if (!IS_ERR(inode)) {
2849                 /* Do not update file c/mtime in ldiskfs. */
2850                 inode->i_flags |= S_NOCMTIME;
2851
2852                 /* For new created object, it must be consistent,
2853                  * and it is unnecessary to scrub against it. */
2854                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
2855
2856                 obj->oo_inode = inode;
2857                 result = 0;
2858         } else {
2859                 if (obj->oo_hl_head != NULL) {
2860                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
2861                         obj->oo_hl_head = NULL;
2862                 }
2863                 result = PTR_ERR(inode);
2864         }
2865         LINVRNT(osd_invariant(obj));
2866         return result;
2867 }
2868
2869 enum {
2870         OSD_NAME_LEN = 255
2871 };
2872
2873 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
2874                      struct lu_attr *attr,
2875                      struct dt_allocation_hint *hint,
2876                      struct dt_object_format *dof,
2877                      struct thandle *th)
2878 {
2879         int result;
2880         struct osd_thandle *oth;
2881         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX | S_ISGID));
2882
2883         LASSERT(S_ISDIR(attr->la_mode));
2884
2885         oth = container_of(th, struct osd_thandle, ot_super);
2886         LASSERT(oth->ot_handle->h_transaction != NULL);
2887         result = osd_mkfile(info, obj, mode, hint, th);
2888
2889         return result;
2890 }
2891
2892 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
2893                         struct lu_attr *attr,
2894                         struct dt_allocation_hint *hint,
2895                         struct dt_object_format *dof,
2896                         struct thandle *th)
2897 {
2898         int result;
2899         struct osd_thandle *oth;
2900         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
2901
2902         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
2903
2904         LASSERT(S_ISREG(attr->la_mode));
2905
2906         oth = container_of(th, struct osd_thandle, ot_super);
2907         LASSERT(oth->ot_handle->h_transaction != NULL);
2908
2909         result = osd_mkfile(info, obj, mode, hint, th);
2910         if (result == 0) {
2911                 LASSERT(obj->oo_inode != NULL);
2912                 if (feat->dif_flags & DT_IND_VARKEY)
2913                         result = iam_lvar_create(obj->oo_inode,
2914                                                  feat->dif_keysize_max,
2915                                                  feat->dif_ptrsize,
2916                                                  feat->dif_recsize_max,
2917                                                  oth->ot_handle);
2918                 else
2919                         result = iam_lfix_create(obj->oo_inode,
2920                                                  feat->dif_keysize_max,
2921                                                  feat->dif_ptrsize,
2922                                                  feat->dif_recsize_max,
2923                                                  oth->ot_handle);
2924
2925         }
2926         return result;
2927 }
2928
2929 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
2930                      struct lu_attr *attr,
2931                      struct dt_allocation_hint *hint,
2932                      struct dt_object_format *dof,
2933                      struct thandle *th)
2934 {
2935         LASSERT(S_ISREG(attr->la_mode));
2936         return osd_mkfile(info, obj, (attr->la_mode &
2937                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2938 }
2939
2940 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
2941                      struct lu_attr *attr,
2942                      struct dt_allocation_hint *hint,
2943                      struct dt_object_format *dof,
2944                      struct thandle *th)
2945 {
2946         LASSERT(S_ISLNK(attr->la_mode));
2947         return osd_mkfile(info, obj, (attr->la_mode &
2948                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2949 }
2950
2951 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
2952                      struct lu_attr *attr,
2953                      struct dt_allocation_hint *hint,
2954                      struct dt_object_format *dof,
2955                      struct thandle *th)
2956 {
2957         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
2958         int result;
2959
2960         LINVRNT(osd_invariant(obj));
2961         LASSERT(obj->oo_inode == NULL);
2962         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
2963                 S_ISFIFO(mode) || S_ISSOCK(mode));
2964
2965         result = osd_mkfile(info, obj, mode, hint, th);
2966         if (result == 0) {
2967                 LASSERT(obj->oo_inode != NULL);
2968                 /*
2969                  * This inode should be marked dirty for i_rdev.  Currently
2970                  * that is done in the osd_attr_init().
2971                  */
2972                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
2973                                    attr->la_rdev);
2974         }
2975         LINVRNT(osd_invariant(obj));
2976         return result;
2977 }
2978
2979 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
2980                               struct lu_attr *,
2981                               struct dt_allocation_hint *hint,
2982                               struct dt_object_format *dof,
2983                               struct thandle *);
2984
2985 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
2986 {
2987         osd_obj_type_f result;
2988
2989         switch (type) {
2990         case DFT_DIR:
2991                 result = osd_mkdir;
2992                 break;
2993         case DFT_REGULAR:
2994                 result = osd_mkreg;
2995                 break;
2996         case DFT_SYM:
2997                 result = osd_mksym;
2998                 break;
2999         case DFT_NODE:
3000                 result = osd_mknod;
3001                 break;
3002         case DFT_INDEX:
3003                 result = osd_mk_index;
3004                 break;
3005
3006         default:
3007                 LBUG();
3008                 break;
3009         }
3010         return result;
3011 }
3012
3013
3014 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
3015                         struct dt_object *parent, struct dt_object *child,
3016                         umode_t child_mode)
3017 {
3018         LASSERT(ah);
3019
3020         ah->dah_parent = parent;
3021         ah->dah_mode = child_mode;
3022
3023         if (parent != NULL && !dt_object_remote(parent)) {
3024                 /* will help to find FID->ino at dt_insert("..") */
3025                 struct osd_object *pobj = osd_dt_obj(parent);
3026                 osd_idc_find_and_init(env, osd_obj2dev(pobj), pobj);
3027         }
3028 }
3029
3030 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
3031                           struct lu_attr *attr, struct dt_object_format *dof)
3032 {
3033         struct inode   *inode = obj->oo_inode;
3034         __u64           valid = attr->la_valid;
3035         int             result;
3036
3037         attr->la_valid &= ~(LA_TYPE | LA_MODE);
3038
3039         if (dof->dof_type != DFT_NODE)
3040                 attr->la_valid &= ~LA_RDEV;
3041         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
3042                 attr->la_valid &= ~LA_ATIME;
3043         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
3044                 attr->la_valid &= ~LA_CTIME;
3045         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
3046                 attr->la_valid &= ~LA_MTIME;
3047
3048         result = osd_quota_transfer(inode, attr);
3049         if (result)
3050                 return;
3051
3052         if (attr->la_valid != 0) {
3053                 result = osd_inode_setattr(info->oti_env, inode, attr);
3054                 /*
3055                  * The osd_inode_setattr() should always succeed here.  The
3056                  * only error that could be returned is EDQUOT when we are
3057                  * trying to change the UID or GID of the inode. However, this
3058                  * should not happen since quota enforcement is no longer
3059                  * enabled on ldiskfs (lquota takes care of it).
3060                  */
3061                 LASSERTF(result == 0, "%d\n", result);
3062                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3063         }
3064
3065         attr->la_valid = valid;
3066 }
3067
3068 /**
3069  * Helper function for osd_create()
3070  *
3071  * \retval 0, on success
3072  */
3073 static int __osd_create(struct osd_thread_info *info, struct osd_object *obj,
3074                         struct lu_attr *attr, struct dt_allocation_hint *hint,
3075                         struct dt_object_format *dof, struct thandle *th)
3076 {
3077         int     result;
3078         __u32   umask;
3079
3080         osd_trans_exec_op(info->oti_env, th, OSD_OT_CREATE);
3081
3082         /* we drop umask so that permissions we pass are not affected */
3083         umask = current->fs->umask;
3084         current->fs->umask = 0;
3085
3086         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
3087                                                   th);
3088         if (likely(obj->oo_inode != NULL)) {
3089                 LASSERT(obj->oo_inode->i_state & I_NEW);
3090
3091                 /* Unlock the inode before attr initialization to avoid
3092                  * unnecessary dqget operations. LU-6378 */
3093                 unlock_new_inode(obj->oo_inode);
3094         }
3095
3096         if (likely(result == 0)) {
3097                 osd_attr_init(info, obj, attr, dof);
3098                 osd_object_init0(obj);
3099         }
3100
3101         /* restore previous umask value */
3102         current->fs->umask = umask;
3103
3104         osd_trans_exec_check(info->oti_env, th, OSD_OT_CREATE);
3105
3106         return result;
3107 }
3108
3109 /**
3110  * Helper function for osd_create()
3111  *
3112  * \retval 0, on success
3113  */
3114 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
3115                            const struct lu_fid *fid, struct thandle *th)
3116 {
3117         struct osd_thread_info *info = osd_oti_get(env);
3118         struct osd_inode_id    *id   = &info->oti_id;
3119         struct osd_device      *osd  = osd_obj2dev(obj);
3120         struct osd_thandle     *oh;
3121         int                     rc;
3122
3123         LASSERT(obj->oo_inode != NULL);
3124
3125         oh = container_of0(th, struct osd_thandle, ot_super);
3126         LASSERT(oh->ot_handle);
3127         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3128
3129         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
3130         rc = osd_oi_insert(info, osd, fid, id, oh->ot_handle,
3131                            OI_CHECK_FLD, NULL);
3132         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3133
3134         return rc;
3135 }
3136
3137 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
3138                    u64 seq, struct lu_seq_range *range)
3139 {
3140         struct seq_server_site  *ss = osd_seq_site(osd);
3141
3142         if (fid_seq_is_idif(seq)) {
3143                 fld_range_set_ost(range);
3144                 range->lsr_index = idif_ost_idx(seq);
3145                 return 0;
3146         }
3147
3148         if (!fid_seq_in_fldb(seq)) {
3149                 fld_range_set_mdt(range);
3150                 if (ss != NULL)
3151                         /* FIXME: If ss is NULL, it suppose not get lsr_index
3152                          * at all */
3153                         range->lsr_index = ss->ss_node_id;
3154                 return 0;
3155         }
3156
3157         LASSERT(ss != NULL);
3158         fld_range_set_any(range);
3159         /* OSD will only do local fld lookup */
3160         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
3161 }
3162
3163 static int osd_declare_create(const struct lu_env *env, struct dt_object *dt,
3164                               struct lu_attr *attr,
3165                               struct dt_allocation_hint *hint,
3166                               struct dt_object_format *dof,
3167                               struct thandle *handle)
3168 {
3169         struct osd_thandle *oh;
3170         int rc;
3171         ENTRY;
3172
3173         LASSERT(handle != NULL);
3174
3175         oh = container_of0(handle, struct osd_thandle, ot_super);
3176         LASSERT(oh->ot_handle == NULL);
3177
3178         /* EA object consumes more credits than regular object: osd_mk_index
3179          * vs. osd_mkreg: osd_mk_index will create 2 blocks for root_node and
3180          * leaf_node, could involves the block, block bitmap, groups, GDT
3181          * change for each block, so add 4 * 2 credits in that case. */
3182         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
3183                              osd_dto_credits_noquota[DTO_OBJECT_CREATE] +
3184                              (dof->dof_type == DFT_INDEX) ? 4 * 2 : 0);
3185         /* Reuse idle OI block may cause additional one OI block
3186          * to be changed. */
3187         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3188                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3189
3190         if (!attr)
3191                 RETURN(0);
3192
3193         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid,
3194                                    attr->la_projid, 1, oh, osd_dt_obj(dt),
3195                                    NULL, OSD_QID_INODE);
3196         if (rc != 0)
3197                 RETURN(rc);
3198
3199         /* will help to find FID->ino mapping at dt_insert() */
3200         rc = osd_idc_find_and_init(env, osd_obj2dev(osd_dt_obj(dt)),
3201                                    osd_dt_obj(dt));
3202
3203         RETURN(rc);
3204 }
3205
3206 /**
3207  * Called to destroy on-disk representation of the object
3208  *
3209  * Concurrency: must be locked
3210  */
3211 static int osd_declare_destroy(const struct lu_env *env, struct dt_object *dt,
3212                                struct thandle *th)
3213 {
3214         struct osd_object  *obj = osd_dt_obj(dt);
3215         struct inode       *inode = obj->oo_inode;
3216         struct osd_thandle *oh;
3217         int                 rc;
3218         ENTRY;
3219
3220         if (inode == NULL)
3221                 RETURN(-ENOENT);
3222
3223         oh = container_of0(th, struct osd_thandle, ot_super);
3224         LASSERT(oh->ot_handle == NULL);
3225
3226         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
3227                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
3228
3229         /* For removing agent entry */
3230         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu))
3231                 oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
3232
3233         /* Recycle idle OI leaf may cause additional three OI blocks
3234          * to be changed. */
3235         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3236                 osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3237                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
3238         /* one less inode */
3239         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3240                                    i_projid_read(inode), -1, oh, obj, NULL,
3241                                    OSD_QID_INODE);
3242         if (rc)
3243                 RETURN(rc);
3244         /* data to be truncated */
3245         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3246                                    i_projid_read(inode), 0, oh, obj, NULL,
3247                                    OSD_QID_BLK);
3248         if (rc)
3249                 RETURN(rc);
3250
3251         /* will help to find FID->ino when this object is being
3252          * added to PENDING/ */
3253         rc = osd_idc_find_and_init(env, osd_obj2dev(obj), obj);
3254
3255         RETURN(rc);
3256 }
3257
3258 static int osd_destroy(const struct lu_env *env, struct dt_object *dt,
3259                        struct thandle *th)
3260 {
3261         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3262         struct osd_object *obj = osd_dt_obj(dt);
3263         struct inode *inode = obj->oo_inode;
3264         struct osd_device *osd = osd_obj2dev(obj);
3265         struct osd_thandle *oh;
3266         int result;
3267         ENTRY;
3268
3269         oh = container_of0(th, struct osd_thandle, ot_super);
3270         LASSERT(oh->ot_handle);
3271         LASSERT(inode);
3272         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
3273
3274         if (unlikely(fid_is_acct(fid)))
3275                 RETURN(-EPERM);
3276
3277         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu)) {
3278                 result = osd_delete_from_remote_parent(env, osd, obj, oh, true);
3279                 if (result != 0)
3280                         CERROR("%s: remove agent entry "DFID": rc = %d\n",
3281                                osd_name(osd), PFID(fid), result);
3282         }
3283
3284         if (S_ISDIR(inode->i_mode)) {
3285                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1 ||
3286                         inode->i_nlink == 2);
3287
3288                 spin_lock(&obj->oo_guard);
3289                 clear_nlink(inode);
3290                 spin_unlock(&obj->oo_guard);
3291                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3292         }
3293
3294         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
3295
3296         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
3297
3298         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3299                 result = osd_oi_delete(osd_oti_get(env), osd, fid,
3300                                        oh->ot_handle, OI_CHECK_FLD);
3301
3302         osd_trans_exec_check(env, th, OSD_OT_DESTROY);
3303         /* XXX: add to ext3 orphan list */
3304         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
3305
3306         /* not needed in the cache anymore */
3307         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
3308         obj->oo_destroyed = 1;
3309
3310         RETURN(0);
3311 }
3312
3313 /**
3314  * Put the fid into lustre_mdt_attrs, and then place the structure
3315  * inode's ea. This fid should not be altered during the life time
3316  * of the inode.
3317  *
3318  * \retval +ve, on success
3319  * \retval -ve, on error
3320  *
3321  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
3322  */
3323 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
3324                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
3325 {
3326         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
3327         struct lustre_mdt_attrs *lma = &loa->loa_lma;
3328         int rc;
3329         ENTRY;
3330
3331         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
3332                 RETURN(0);
3333
3334         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_OST_EA_FID_SET))
3335                 rc = -ENOMEM;
3336
3337         lustre_loa_init(loa, fid, compat, incompat);
3338         lustre_loa_swab(loa, false);
3339
3340         /* For the OST device with 256 bytes inode size by default,
3341          * the PFID EA will be stored together with LMA EA to avoid
3342          * performance trouble. Otherwise the PFID EA can be stored
3343          * independently. LU-8998 */
3344         if ((compat & LMAC_FID_ON_OST) &&
3345             LDISKFS_INODE_SIZE(inode->i_sb) <= 256)
3346                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3347                                      sizeof(*loa), XATTR_CREATE);
3348         else
3349                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3350                                      sizeof(*lma), XATTR_CREATE);
3351         /* LMA may already exist, but we need to check that all the
3352          * desired compat/incompat flags have been added. */
3353         if (unlikely(rc == -EEXIST)) {
3354                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
3355                                      XATTR_NAME_LMA, (void *)loa, sizeof(*loa));
3356                 if (rc < 0)
3357                         RETURN(rc);
3358
3359                 if (rc < sizeof(*lma))
3360                         RETURN(-EINVAL);
3361
3362                 lustre_loa_swab(loa, true);
3363                 if (lu_fid_eq(fid, &lma->lma_self_fid) &&
3364                     ((compat == 0 && incompat == 0) ||
3365                      (!(~lma->lma_compat & compat) &&
3366                       !(~lma->lma_incompat & incompat))))
3367                         RETURN(0);
3368
3369                 lma->lma_self_fid = *fid;
3370                 lma->lma_compat |= compat;
3371                 lma->lma_incompat |= incompat;
3372                 if (rc == sizeof(*lma)) {
3373                         lustre_lma_swab(lma);
3374                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3375                                              sizeof(*lma), XATTR_REPLACE);
3376                 } else {
3377                         lustre_loa_swab(loa, false);
3378                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3379                                              sizeof(*loa), XATTR_REPLACE);
3380                 }
3381         }
3382
3383         RETURN(rc);
3384 }
3385
3386 /**
3387  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
3388  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
3389  * To have compatilibility with 1.8 ldiskfs driver we need to have
3390  * magic number at start of fid data.
3391  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
3392  * its inmemory API.
3393  */
3394 static void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
3395                                          const struct lu_fid *fid)
3396 {
3397         if (!fid_is_namespace_visible(fid) ||
3398             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
3399                 param->edp_magic = 0;
3400                 return;
3401         }
3402
3403         param->edp_magic = LDISKFS_LUFID_MAGIC;
3404         param->edp_len =  sizeof(struct lu_fid) + 1;
3405         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
3406 }
3407
3408 /**
3409  * Try to read the fid from inode ea into dt_rec.
3410  *
3411  * \param fid object fid.
3412  *
3413  * \retval 0 on success
3414  */
3415 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
3416                           __u32 ino, struct lu_fid *fid,
3417                           struct osd_inode_id *id)
3418 {
3419         struct osd_thread_info *info  = osd_oti_get(env);
3420         struct inode           *inode;
3421         ENTRY;
3422
3423         osd_id_gen(id, ino, OSD_OII_NOGEN);
3424         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
3425         if (IS_ERR(inode))
3426                 RETURN(PTR_ERR(inode));
3427
3428         iput(inode);
3429         RETURN(0);
3430 }
3431
3432 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
3433                                         struct inode *dir,
3434                                         struct inode *parent_dir,
3435                                         const struct lu_fid *dot_fid,
3436                                         const struct lu_fid *dot_dot_fid,
3437                                         struct osd_thandle *oth)
3438 {
3439         struct ldiskfs_dentry_param *dot_ldp;
3440         struct ldiskfs_dentry_param *dot_dot_ldp;
3441         __u32 saved_nlink = dir->i_nlink;
3442         int rc;
3443
3444         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
3445         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
3446
3447         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3448         dot_ldp->edp_magic = 0;
3449
3450         rc = ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
3451                                     dir, dot_ldp, dot_dot_ldp);
3452         /* The ldiskfs_add_dot_dotdot() may dir->i_nlink as 2, then
3453          * the subseqent ref_add() will increase the dir->i_nlink
3454          * as 3. That is incorrect for new created directory.
3455          *
3456          * It looks like hack, because we want to make the OSD API
3457          * to be order-independent for new created directory object
3458          * between dt_insert(..) and ref_add() operations.
3459          *
3460          * Here, we only restore the in-RAM dir-inode's nlink attr,
3461          * becuase if the nlink attr is not 2, then there will be
3462          * ref_add() called following the dt_insert(..), such call
3463          * will make both the in-RAM and on-disk dir-inode's nlink
3464          * attr to be set as 2. LU-7447 */
3465         set_nlink(dir, saved_nlink);
3466         return rc;
3467 }
3468
3469 /**
3470  * Create an local agent inode for remote entry
3471  */
3472 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
3473                                                   struct osd_device *osd,
3474                                                   struct osd_object *pobj,
3475                                                   const struct lu_fid *fid,
3476                                                   __u32 type,
3477                                                   struct thandle *th)
3478 {
3479         struct osd_thread_info  *info = osd_oti_get(env);
3480         struct inode            *local;
3481         struct osd_thandle      *oh;
3482         int                     rc;
3483         ENTRY;
3484
3485         LASSERT(th);
3486         oh = container_of(th, struct osd_thandle, ot_super);
3487         LASSERT(oh->ot_handle->h_transaction != NULL);
3488
3489         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, type);
3490         if (IS_ERR(local)) {
3491                 CERROR("%s: create local error %d\n", osd_name(osd),
3492                        (int)PTR_ERR(local));
3493                 RETURN(local);
3494         }
3495
3496         /* restore i_gid in case S_ISGID is set, we will inherit S_ISGID and set
3497          * correct gid on remote file, not agent here */
3498         local->i_gid = current_fsgid();
3499         ldiskfs_set_inode_state(local, LDISKFS_STATE_LUSTRE_NOSCRUB);
3500         unlock_new_inode(local);
3501
3502         /* Agent inode should not have project ID */
3503 #ifdef  HAVE_PROJECT_QUOTA
3504         if (LDISKFS_I(pobj->oo_inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
3505             i_projid_read(pobj->oo_inode) != 0) {
3506                 rc = ldiskfs_transfer_project(local, 0);
3507                 if (rc) {
3508                         CERROR("%s: quota transfer failed: rc = %d. Is project "
3509                                "quota enforcement enabled on the ldiskfs "
3510                                "filesystem?\n", local->i_sb->s_id, rc);
3511                         RETURN(ERR_PTR(rc));
3512                 }
3513         }
3514 #endif
3515         /* Set special LMA flag for local agent inode */
3516         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
3517         if (rc != 0) {
3518                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
3519                        osd_name(osd), PFID(fid), rc);
3520                 RETURN(ERR_PTR(rc));
3521         }
3522
3523         if (!S_ISDIR(type))
3524                 RETURN(local);
3525
3526         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
3527                                          lu_object_fid(&pobj->oo_dt.do_lu),
3528                                          fid, oh);
3529         if (rc != 0) {
3530                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
3531                         osd_name(osd), PFID(fid), rc);
3532                 RETURN(ERR_PTR(rc));
3533         }
3534
3535         RETURN(local);
3536 }
3537
3538 /**
3539  * when direntry is deleted, we have to take care of possible agent inode
3540  * referenced by that. unfortunately we can't do this at that point:
3541  * iget() within a running transaction leads to deadlock and we better do
3542  * not call that every delete declaration to save performance. so we put
3543  * a potention agent inode on a list and process that once the transaction
3544  * is over. Notice it's not any worse in terms of real orphans as regular
3545  * object destroy doesn't put inodes on the on-disk orphan list. this should
3546  * be addressed separately
3547  */
3548 static int osd_schedule_agent_inode_removal(const struct lu_env *env,
3549                                             struct osd_thandle *oh,
3550                                             __u32 ino)
3551 {
3552         struct osd_device      *osd = osd_dt_dev(oh->ot_super.th_dev);
3553         struct osd_obj_orphan *oor;
3554
3555         OBD_ALLOC_PTR(oor);
3556         if (oor == NULL)
3557                 return -ENOMEM;
3558
3559         oor->oor_ino = ino;
3560         oor->oor_env = (struct lu_env *)env;
3561         spin_lock(&osd->od_osfs_lock);
3562         list_add(&oor->oor_list, &osd->od_orphan_list);
3563         spin_unlock(&osd->od_osfs_lock);
3564
3565         oh->ot_remove_agents = 1;
3566
3567         return 0;
3568
3569 }
3570
3571 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
3572                                                 struct osd_device *osd)
3573 {
3574         struct osd_thread_info *info = osd_oti_get(env);
3575         struct osd_obj_orphan *oor, *tmp;
3576         struct osd_inode_id id;
3577         struct list_head list;
3578         struct inode *inode;
3579         struct lu_fid fid;
3580         handle_t *jh;
3581         __u32 ino;
3582
3583         INIT_LIST_HEAD(&list);
3584
3585         spin_lock(&osd->od_osfs_lock);
3586         list_for_each_entry_safe(oor, tmp, &osd->od_orphan_list, oor_list) {
3587                 if (oor->oor_env == env) {
3588                         list_del(&oor->oor_list);
3589                         list_add(&oor->oor_list, &list);
3590                 }
3591         }
3592         spin_unlock(&osd->od_osfs_lock);
3593
3594         list_for_each_entry_safe(oor, tmp, &list, oor_list) {
3595
3596                 ino = oor->oor_ino;
3597
3598                 list_del(&oor->oor_list);
3599                 OBD_FREE_PTR(oor);
3600
3601                 osd_id_gen(&id, ino, OSD_OII_NOGEN);
3602                 inode = osd_iget_fid(info, osd, &id, &fid);
3603                 if (IS_ERR(inode))
3604                         continue;
3605
3606                 if (!osd_remote_fid(env, osd, &fid)) {
3607                         iput(inode);
3608                         continue;
3609                 }
3610
3611                 jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC, 1);
3612                 clear_nlink(inode);
3613                 mark_inode_dirty(inode);
3614                 ldiskfs_journal_stop(jh);
3615                 iput(inode);
3616         }
3617
3618         return 0;
3619 }
3620
3621 /**
3622  * OSD layer object create function for OST objects (b=11826).
3623  *
3624  * The FID is inserted into inode xattr here.
3625  *
3626  * \retval   0, on success
3627  * \retval -ve, on error
3628  */
3629 static int osd_create(const struct lu_env *env, struct dt_object *dt,
3630                       struct lu_attr *attr, struct dt_allocation_hint *hint,
3631                       struct dt_object_format *dof, struct thandle *th)
3632 {
3633         const struct lu_fid     *fid    = lu_object_fid(&dt->do_lu);
3634         struct osd_object       *obj    = osd_dt_obj(dt);
3635         struct osd_thread_info  *info   = osd_oti_get(env);
3636         int                      result, on_ost = 0;
3637
3638         ENTRY;
3639
3640         if (dt_object_exists(dt))
3641                 RETURN(-EEXIST);
3642
3643         LINVRNT(osd_invariant(obj));
3644         LASSERT(!dt_object_remote(dt));
3645         LASSERT(osd_is_write_locked(env, obj));
3646         LASSERT(th != NULL);
3647
3648         if (unlikely(fid_is_acct(fid)))
3649                 /* Quota files can't be created from the kernel any more,
3650                  * 'tune2fs -O quota' will take care of creating them */
3651                 RETURN(-EPERM);
3652
3653         result = __osd_create(info, obj, attr, hint, dof, th);
3654         if (result == 0) {
3655                 if (fid_is_idif(fid) &&
3656                     !osd_dev(dt->do_lu.lo_dev)->od_index_in_idif) {
3657                         struct lu_fid *tfid = &info->oti_fid;
3658                         struct ost_id *oi   = &info->oti_ostid;
3659
3660                         fid_to_ostid(fid, oi);
3661                         ostid_to_fid(tfid, oi, 0);
3662                         on_ost = 1;
3663                         result = osd_ea_fid_set(info, obj->oo_inode, tfid,
3664                                                 LMAC_FID_ON_OST, 0);
3665                 } else {
3666                         on_ost = fid_is_on_ost(info, osd_obj2dev(obj),
3667                                                fid, OI_CHECK_FLD);
3668                         result = osd_ea_fid_set(info, obj->oo_inode, fid,
3669                                                 on_ost ? LMAC_FID_ON_OST : 0,
3670                                                 0);
3671                 }
3672                 if (obj->oo_dt.do_body_ops == &osd_body_ops_new)
3673                         obj->oo_dt.do_body_ops = &osd_body_ops;
3674         }
3675
3676         if (!result && !CFS_FAIL_CHECK(OBD_FAIL_OSD_NO_OI_ENTRY))
3677                 result = __osd_oi_insert(env, obj, fid, th);
3678
3679         /* a small optimization - dt_insert() isn't usually applied
3680          * to OST objects, so we don't need to cache OI mapping for
3681          * OST objects */
3682         if (result == 0 && on_ost == 0) {
3683                 struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
3684                 result = osd_idc_find_and_init(env, osd, obj);
3685                 LASSERT(result == 0);
3686         }
3687
3688         LASSERT(ergo(result == 0,
3689                      dt_object_exists(dt) && !dt_object_remote(dt)));
3690         LINVRNT(osd_invariant(obj));
3691         RETURN(result);
3692 }
3693
3694 static int osd_declare_ref_add(const struct lu_env *env, struct dt_object *dt,
3695                                struct thandle *handle)
3696 {
3697         struct osd_thandle *oh;
3698
3699         /* it's possible that object doesn't exist yet */
3700         LASSERT(handle != NULL);
3701
3702         oh = container_of0(handle, struct osd_thandle, ot_super);
3703         LASSERT(oh->ot_handle == NULL);
3704
3705         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
3706                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
3707
3708         osd_idc_find_and_init(env, osd_dev(dt->do_lu.lo_dev), osd_dt_obj(dt));
3709
3710         return 0;
3711 }
3712
3713 /*
3714  * Concurrency: @dt is write locked.
3715  */
3716 static int osd_ref_add(const struct lu_env *env, struct dt_object *dt,
3717                        struct thandle *th)
3718 {
3719         struct osd_object  *obj = osd_dt_obj(dt);
3720         struct inode       *inode = obj->oo_inode;
3721         struct osd_thandle *oh;
3722         int                 rc = 0;
3723
3724         if (!dt_object_exists(dt) || obj->oo_destroyed)
3725                 return -ENOENT;
3726
3727         LINVRNT(osd_invariant(obj));
3728         LASSERT(!dt_object_remote(dt));
3729         LASSERT(osd_is_write_locked(env, obj));
3730         LASSERT(th != NULL);
3731
3732         oh = container_of0(th, struct osd_thandle, ot_super);
3733         LASSERT(oh->ot_handle != NULL);
3734
3735         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
3736
3737         CDEBUG(D_INODE, DFID" increase nlink %d\n",
3738                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
3739         /*
3740          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
3741          * (65000) subdirectories by storing "1" in i_nlink if the link count
3742          * would otherwise overflow. Directory tranversal tools understand
3743          * that (st_nlink == 1) indicates that the filesystem dose not track
3744          * hard links count on the directory, and will not abort subdirectory
3745          * scanning early once (st_nlink - 2) subdirs have been found.
3746          *
3747          * This also has to properly handle the case of inodes with nlink == 0
3748          * in case they are being linked into the PENDING directory
3749          */
3750         spin_lock(&obj->oo_guard);
3751         if (unlikely(inode->i_nlink == 0))
3752                 /* inc_nlink from 0 may cause WARN_ON */
3753                 set_nlink(inode, 1);
3754         else {
3755                 ldiskfs_inc_count(oh->ot_handle, inode);
3756                 if (!S_ISDIR(inode->i_mode))
3757                         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
3758         }
3759         spin_unlock(&obj->oo_guard);
3760
3761         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3762         LINVRNT(osd_invariant(obj));
3763
3764         osd_trans_exec_check(env, th, OSD_OT_REF_ADD);
3765
3766         return rc;
3767 }
3768
3769 static int osd_declare_ref_del(const struct lu_env *env, struct dt_object *dt,
3770                                struct thandle *handle)
3771 {
3772         struct osd_thandle *oh;
3773
3774         if (!dt_object_exists(dt))
3775                 return -ENOENT;
3776
3777         LASSERT(!dt_object_remote(dt));
3778         LASSERT(handle != NULL);
3779
3780         oh = container_of0(handle, struct osd_thandle, ot_super);
3781         LASSERT(oh->ot_handle == NULL);
3782
3783         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
3784                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
3785
3786         return 0;
3787 }
3788
3789 /*
3790  * Concurrency: @dt is write locked.
3791  */
3792 static int osd_ref_del(const struct lu_env *env, struct dt_object *dt,
3793                        struct thandle *th)
3794 {
3795         struct osd_object       *obj = osd_dt_obj(dt);
3796         struct inode            *inode = obj->oo_inode;
3797         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
3798         struct osd_thandle      *oh;
3799
3800         if (!dt_object_exists(dt))
3801                 return -ENOENT;
3802
3803         LINVRNT(osd_invariant(obj));
3804         LASSERT(!dt_object_remote(dt));
3805         LASSERT(osd_is_write_locked(env, obj));
3806         LASSERT(th != NULL);
3807
3808         oh = container_of0(th, struct osd_thandle, ot_super);
3809         LASSERT(oh->ot_handle != NULL);
3810
3811         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
3812
3813         spin_lock(&obj->oo_guard);
3814         /* That can be result of upgrade from old Lustre version and
3815          * applied only to local files.  Just skip this ref_del call.
3816          * ext4_unlink() only treats this as a warning, don't LASSERT here.*/
3817         if (inode->i_nlink == 0) {
3818                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
3819                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
3820                              ", maybe an upgraded file? (LU-3915)\n",
3821                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
3822                 spin_unlock(&obj->oo_guard);
3823                 return 0;
3824         }
3825
3826         CDEBUG(D_INODE, DFID" decrease nlink %d\n",
3827                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
3828
3829         ldiskfs_dec_count(oh->ot_handle, inode);
3830         spin_unlock(&obj->oo_guard);
3831
3832         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3833         LINVRNT(osd_invariant(obj));
3834
3835         osd_trans_exec_check(env, th, OSD_OT_REF_DEL);
3836
3837         return 0;
3838 }
3839
3840 /*
3841  * Concurrency: @dt is read locked.
3842  */
3843 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
3844                          struct lu_buf *buf, const char *name)
3845 {
3846         struct osd_object      *obj    = osd_dt_obj(dt);
3847         struct inode           *inode  = obj->oo_inode;
3848         struct osd_thread_info *info   = osd_oti_get(env);
3849         struct dentry          *dentry = &info->oti_obj_dentry;
3850         bool                    cache_xattr = false;
3851         int                     rc;
3852
3853         LASSERT(buf);
3854
3855         /* version get is not real XATTR but uses xattr API */
3856         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
3857                 dt_obj_version_t *ver = buf->lb_buf;
3858
3859                 /* for version we are just using xattr API but change inode
3860                  * field instead */
3861                 if (buf->lb_len == 0)
3862                         return sizeof(dt_obj_version_t);
3863
3864                 if (buf->lb_len < sizeof(dt_obj_version_t))
3865                         return -ERANGE;
3866
3867                 CDEBUG(D_INODE, "Get version %#llx for inode %lu\n",
3868                        LDISKFS_I(inode)->i_fs_version, inode->i_ino);
3869
3870                 *ver = LDISKFS_I(inode)->i_fs_version;
3871
3872                 return sizeof(dt_obj_version_t);
3873         }
3874
3875         if (!dt_object_exists(dt))
3876                 return -ENOENT;
3877
3878         LASSERT(!dt_object_remote(dt));
3879         LASSERT(inode->i_op != NULL);
3880         LASSERT(inode->i_op->getxattr != NULL);
3881
3882         if (strcmp(name, XATTR_NAME_LOV) == 0 ||
3883             strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
3884                 cache_xattr = true;
3885
3886         if (cache_xattr) {
3887                 rc = osd_oxc_get(obj, name, buf);
3888                 if (rc != -ENOENT)
3889                         return rc;
3890         }
3891
3892         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
3893                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
3894                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
3895                 struct filter_fid *ff;
3896                 struct ost_layout *ol;
3897
3898                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
3899                 if (rc)
3900                         return rc;
3901
3902                 LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
3903
3904                 rc = sizeof(*ff);
3905                 if (buf->lb_len == 0 || !buf->lb_buf)
3906                         return rc;
3907
3908                 if (buf->lb_len < rc)
3909                         return -ERANGE;
3910
3911                 ff = buf->lb_buf;
3912                 ol = &ff->ff_layout;
3913                 ol->ol_stripe_count = cpu_to_le32(loa->loa_parent_fid.f_ver >>
3914                                                   PFID_STRIPE_IDX_BITS);
3915                 ol->ol_stripe_size = cpu_to_le32(loa->loa_stripe_size);
3916                 loa->loa_parent_fid.f_ver &= PFID_STRIPE_COUNT_MASK;
3917                 fid_cpu_to_le(&ff->ff_parent, &loa->loa_parent_fid);
3918                 if (lma->lma_compat & LMAC_COMP_INFO) {
3919                         ol->ol_comp_start = cpu_to_le64(loa->loa_comp_start);
3920                         ol->ol_comp_end = cpu_to_le64(loa->loa_comp_end);
3921                         ol->ol_comp_id = cpu_to_le32(loa->loa_comp_id);
3922                 } else {
3923                         ol->ol_comp_start = 0;
3924                         ol->ol_comp_end = 0;
3925                         ol->ol_comp_id = 0;
3926                 }
3927         } else {
3928                 rc = __osd_xattr_get(inode, dentry, name,
3929                                      buf->lb_buf, buf->lb_len);
3930         }
3931
3932         if (cache_xattr) {
3933                 if (rc == -ENOENT || rc == -ENODATA)
3934                         osd_oxc_add(obj, name, NULL, 0);
3935                 else if (rc > 0 && buf->lb_buf != NULL)
3936                         osd_oxc_add(obj, name, buf->lb_buf, rc);
3937         }
3938
3939         return rc;
3940 }
3941
3942 static int osd_declare_xattr_set(const struct lu_env *env,
3943                                  struct dt_object *dt,
3944                                  const struct lu_buf *buf, const char *name,
3945                                  int fl, struct thandle *handle)
3946 {
3947         struct osd_thandle *oh;
3948         int credits = 0;
3949         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3950
3951         LASSERT(handle != NULL);
3952
3953         oh = container_of0(handle, struct osd_thandle, ot_super);
3954         LASSERT(oh->ot_handle == NULL);
3955
3956         if (strcmp(name, XATTR_NAME_LMA) == 0) {
3957                 /* For non-upgrading case, the LMA is set first and
3958                  * usually fit inode. But for upgrade case, the LMA
3959                  * may be in another separated EA block. */
3960                 if (dt_object_exists(dt)) {
3961                         if (fl == LU_XATTR_REPLACE)
3962                                 credits = 1;
3963                         else
3964                                 goto upgrade;
3965                 }
3966         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
3967                 credits = 1;
3968         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
3969                 /* We may need to delete the old PFID EA. */
3970                 credits = LDISKFS_MAXQUOTAS_DEL_BLOCKS(sb);
3971                 if (fl == LU_XATTR_REPLACE)
3972                         credits += 1;
3973                 else
3974                         goto upgrade;
3975         } else {
3976                 /* If some name entry resides on remote MDT, then will create
3977                  * agent entry under remote parent. On the other hand, if the
3978                  * remote entry will be removed, then related agent entry may
3979                  * need to be removed from the remote parent. So there may be
3980                  * kinds of cases, let's declare enough credits. The credits
3981                  * for create agent entry is enough for remove case. */
3982                 if (strcmp(name, XATTR_NAME_LINK) == 0) {
3983                         credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
3984                         if (dt_object_exists(dt))
3985                                 credits += 1; /* For updating LMA */
3986                 }
3987
3988 upgrade:
3989                 credits += osd_dto_credits_noquota[DTO_XATTR_SET];
3990
3991                 if (buf != NULL) {
3992                         ssize_t buflen;
3993
3994                         if (buf->lb_buf == NULL && dt_object_exists(dt)) {
3995                                 /* learn xattr size from osd_xattr_get if
3996                                    attribute has not been read yet */
3997                                 buflen = __osd_xattr_get(
3998                                     osd_dt_obj(dt)->oo_inode,
3999                                     &osd_oti_get(env)->oti_obj_dentry,
4000                                     name, NULL, 0);
4001                                 if (buflen < 0)
4002                                         buflen = 0;
4003                         } else {
4004                                 buflen = buf->lb_len;
4005                         }
4006
4007                         if (buflen > sb->s_blocksize) {
4008                                 credits += osd_calc_bkmap_credits(
4009                                     sb, NULL, 0, -1,
4010                                     (buflen + sb->s_blocksize - 1) >>
4011                                     sb->s_blocksize_bits);
4012                         }
4013                 }
4014                 /*
4015                  * xattr set may involve inode quota change, reserve credits for
4016                  * dquot_initialize()
4017                  */
4018                 credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4019         }
4020
4021         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
4022
4023         return 0;
4024 }
4025
4026 static int osd_xattr_set_pfid(const struct lu_env *env, struct osd_object *obj,
4027                               const struct lu_buf *buf, int fl,
4028                               struct thandle *handle)
4029 {
4030         struct osd_thread_info *info = osd_oti_get(env);
4031         struct dentry *dentry = &info->oti_obj_dentry;
4032         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4033         struct lustre_mdt_attrs *lma = &loa->loa_lma;
4034         struct inode *inode = obj->oo_inode;
4035         struct filter_fid *ff = buf->lb_buf;
4036         struct ost_layout *ol = &ff->ff_layout;
4037         int flags = XATTR_REPLACE;
4038         int rc;
4039         ENTRY;
4040
4041         if (buf->lb_len != sizeof(*ff) && buf->lb_len != sizeof(struct lu_fid))
4042                 RETURN(-EINVAL);
4043
4044         rc = osd_get_lma(info, inode, dentry, loa);
4045         if (rc == -ENODATA) {
4046                 /* Usually for upgarding from old device */
4047                 lustre_loa_init(loa, lu_object_fid(&obj->oo_dt.do_lu),
4048                                 LMAC_FID_ON_OST, 0);
4049                 flags = XATTR_CREATE;
4050         } else if (rc) {
4051                 RETURN(rc);
4052         }
4053
4054         if (!rc && lma->lma_compat & LMAC_STRIPE_INFO) {
4055                 if ((fl & LU_XATTR_CREATE) && !(fl & LU_XATTR_REPLACE))
4056                         RETURN(-EEXIST);
4057
4058                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256) {
4059                         /* Separate PFID EA from LMA */
4060                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4061                         lustre_lma_swab(lma);
4062                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4063                                              sizeof(*lma), XATTR_REPLACE);
4064                         if (!rc) {
4065                                 obj->oo_pfid_in_lma = 0;
4066                                 rc = LU_XATTR_CREATE;
4067                         }
4068
4069                         RETURN(rc);
4070                 }
4071         } else {
4072                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256)
4073                         RETURN(fl);
4074
4075                 /* Old client does not send stripe information,
4076                  * then store the PFID EA on disk separatedly. */
4077                 if (unlikely(buf->lb_len == sizeof(struct lu_fid) ||
4078                              ol->ol_stripe_size == 0))
4079                         RETURN(fl);
4080
4081                 /* Remove old PFID EA entry firstly. */
4082                 ll_vfs_dq_init(inode);
4083                 rc = inode->i_op->removexattr(dentry, XATTR_NAME_FID);
4084                 if (rc == -ENODATA) {
4085                         if ((fl & LU_XATTR_REPLACE) && !(fl & LU_XATTR_CREATE))
4086                                 RETURN(rc);
4087                 } else if (rc) {
4088                         RETURN(rc);
4089                 }
4090         }
4091
4092         fid_le_to_cpu(&loa->loa_parent_fid, &ff->ff_parent);
4093         if (likely(ol->ol_stripe_size != 0)) {
4094                 loa->loa_parent_fid.f_ver |= le32_to_cpu(ol->ol_stripe_count) <<
4095                                              PFID_STRIPE_IDX_BITS;
4096                 loa->loa_stripe_size = le32_to_cpu(ol->ol_stripe_size);
4097                 lma->lma_compat |= LMAC_STRIPE_INFO;
4098                 if (ol->ol_comp_id != 0) {
4099                         loa->loa_comp_id = le32_to_cpu(ol->ol_comp_id);
4100                         loa->loa_comp_start = le64_to_cpu(ol->ol_comp_start);
4101                         loa->loa_comp_end = le64_to_cpu(ol->ol_comp_end);
4102                         lma->lma_compat |= LMAC_COMP_INFO;
4103                 }
4104         }
4105
4106         lustre_loa_swab(loa, false);
4107
4108         /* Store the PFID EA inside LMA. */
4109         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa, sizeof(*loa),
4110                              flags);
4111         if (!rc)
4112                 obj->oo_pfid_in_lma = 1;
4113
4114         RETURN(rc);
4115 }
4116
4117 /*
4118  * In DNE environment, the object (in spite of regular file or directory)
4119  * and its name entry may reside on different MDTs. Under such case, we will
4120  * create an agent entry on the MDT where the object resides. The agent entry
4121  * references the object locally, that makes the object to be visible to the
4122  * userspace when mounted as 'ldiskfs' directly. Then the userspace tools,
4123  * such as 'tar' can handle the object properly.
4124  *
4125  * We handle the agent entry during set linkEA that is the common interface
4126  * for both regular file and directroy, can handle kinds of cases, such as
4127  * create/link/unlink/rename, and so on.
4128  *
4129  * NOTE: we can NOT do that when ea_{insert,delete} that is only for directory.
4130  *
4131  * XXX: There are two known issues:
4132  * 1. For one object, we will create at most one agent entry even if there
4133  *    may be more than one cross-MDTs hard links on the object. So the local
4134  *    e2fsck may claim that the object's nlink is larger than the name entries
4135  *    that reference such inode. And in further, the e2fsck will fix the nlink
4136  *    attribute to match the local references. Then it will cause the object's
4137  *    nlink attribute to be inconsistent with the global references. it is bad
4138  *    but not fatal. The ref_del() can handle the zero-referenced case. On the
4139  *    other hand, the global namespace LFSCK can repair the object's attribute
4140  *    according to the linkEA.
4141  * 2. There may be too many hard links on the object as to its linkEA overflow,
4142  *    then the linkEA entry for cross-MDTs reference may be discarded. If such
4143  *    case happened, then at this point, we do not know whether there are some
4144  *    cross-MDTs reference. But there are local references, it guarantees that
4145  *    object is visible to userspace when mounted as 'ldiskfs'. That is enough.
4146  */
4147 static int osd_xattr_handle_linkea(const struct lu_env *env,
4148                                    struct osd_device *osd,
4149                                    struct osd_object *obj,
4150                                    const struct lu_buf *buf,
4151                                    struct thandle *handle)
4152 {
4153         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
4154         struct lu_fid *tfid = &osd_oti_get(env)->oti_fid3;
4155         struct linkea_data ldata = { .ld_buf = (struct lu_buf *)buf };
4156         struct lu_name tmpname;
4157         struct osd_thandle *oh;
4158         int rc;
4159         bool remote = false;
4160         ENTRY;
4161
4162         oh = container_of0(handle, struct osd_thandle, ot_super);
4163         LASSERT(oh->ot_handle != NULL);
4164
4165         rc = linkea_init_with_rec(&ldata);
4166         if (!rc) {
4167                 linkea_first_entry(&ldata);
4168                 while (ldata.ld_lee != NULL && !remote) {
4169                         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen,
4170                                             &tmpname, tfid);
4171                         if (osd_remote_fid(env, osd, tfid) > 0)
4172                                 remote = true;
4173                         else
4174                                 linkea_next_entry(&ldata);
4175                 }
4176         } else if (rc == -ENODATA) {
4177                 rc = 0;
4178         } else {
4179                 RETURN(rc);
4180         }
4181
4182         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu) && !remote) {
4183                 rc = osd_delete_from_remote_parent(env, osd, obj, oh, false);
4184                 if (rc)
4185                         CERROR("%s: failed to remove agent entry for "DFID
4186                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4187         } else if (!lu_object_has_agent_entry(&obj->oo_dt.do_lu) && remote) {
4188                 rc = osd_add_to_remote_parent(env, osd, obj, oh);
4189                 if (rc)
4190                         CERROR("%s: failed to create agent entry for "DFID
4191                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4192         }
4193
4194         RETURN(rc);
4195 }
4196
4197 /*
4198  * Concurrency: @dt is write locked.
4199  */
4200 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
4201                          const struct lu_buf *buf, const char *name, int fl,
4202                          struct thandle *handle)
4203 {
4204         struct osd_object *obj = osd_dt_obj(dt);
4205         struct osd_device *osd = osd_obj2dev(obj);
4206         struct inode *inode = obj->oo_inode;
4207         struct osd_thread_info *info = osd_oti_get(env);
4208         int fs_flags = 0;
4209         int len;
4210         int rc;
4211         ENTRY;
4212
4213         LASSERT(handle);
4214         LASSERT(buf);
4215
4216         /* version set is not real XATTR */
4217         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4218                 dt_obj_version_t *version = buf->lb_buf;
4219
4220                 /* for version we are just using xattr API but change inode
4221                  * field instead */
4222                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
4223
4224                 CDEBUG(D_INODE, "Set version %#llx (old %#llx) for inode %lu\n",
4225                        *version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4226
4227                 LDISKFS_I(inode)->i_fs_version = *version;
4228                 /* Version is set after all inode operations are finished,
4229                  * so we should mark it dirty here */
4230                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
4231
4232                 RETURN(0);
4233         }
4234
4235         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zu\n",
4236                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
4237
4238         len = buf->lb_len;
4239         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4240
4241         /* For the OST device with 256 bytes inode size by default,
4242          * the PFID EA will be stored together with LMA EA to avoid
4243          * performance trouble. Otherwise the PFID EA can be stored
4244          * independently. LU-8998 */
4245         if (strcmp(name, XATTR_NAME_FID) == 0 && osd->od_is_ost &&
4246             (LDISKFS_INODE_SIZE(inode->i_sb) <= 256 || obj->oo_pfid_in_lma)) {
4247                 LASSERT(buf->lb_buf);
4248
4249                 fl = osd_xattr_set_pfid(env, obj, buf, fl, handle);
4250                 if (fl <= 0)
4251                         RETURN(fl);
4252         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
4253                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4254                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4255
4256                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4257                 if (rc)
4258                         RETURN(rc);
4259
4260                 lma->lma_incompat |= LMAI_STRIPED;
4261                 lustre_lma_swab(lma);
4262                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4263                                      sizeof(*lma), XATTR_REPLACE);
4264                 if (rc != 0)
4265                         RETURN(rc);
4266         } else if (strcmp(name, XATTR_NAME_LINK) == 0) {
4267                 LASSERT(!osd->od_is_ost);
4268
4269                 rc = osd_xattr_handle_linkea(env, osd, obj, buf, handle);
4270                 if (rc)
4271                         RETURN(rc);
4272         }
4273
4274         if (fl & LU_XATTR_REPLACE)
4275                 fs_flags |= XATTR_REPLACE;
4276
4277         if (fl & LU_XATTR_CREATE)
4278                 fs_flags |= XATTR_CREATE;
4279
4280         rc = __osd_xattr_set(info, inode, name, buf->lb_buf, len, fs_flags);
4281         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4282
4283         if (rc == 0 &&
4284             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4285              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4286                 osd_oxc_add(obj, name, buf->lb_buf, buf->lb_len);
4287
4288         return rc;
4289 }
4290
4291 /*
4292  * Concurrency: @dt is read locked.
4293  */
4294 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
4295                           const struct lu_buf *buf)
4296 {
4297         struct osd_object      *obj    = osd_dt_obj(dt);
4298         struct inode           *inode  = obj->oo_inode;
4299         struct osd_thread_info *info   = osd_oti_get(env);
4300         struct dentry          *dentry = &info->oti_obj_dentry;
4301
4302         if (!dt_object_exists(dt))
4303                 return -ENOENT;
4304
4305         LASSERT(!dt_object_remote(dt));
4306         LASSERT(inode->i_op != NULL);
4307         LASSERT(inode->i_op->listxattr != NULL);
4308
4309         dentry->d_inode = inode;
4310         dentry->d_sb = inode->i_sb;
4311         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
4312 }
4313
4314 static int osd_declare_xattr_del(const struct lu_env *env,
4315                                  struct dt_object *dt, const char *name,
4316                                  struct thandle *handle)
4317 {
4318         struct osd_thandle *oh;
4319         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4320
4321         LASSERT(!dt_object_remote(dt));
4322         LASSERT(handle != NULL);
4323
4324         oh = container_of0(handle, struct osd_thandle, ot_super);
4325         LASSERT(oh->ot_handle == NULL);
4326
4327         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
4328                              osd_dto_credits_noquota[DTO_XATTR_SET]);
4329         /*
4330          * xattr del may involve inode quota change, reserve credits for
4331          * dquot_initialize()
4332          */
4333         oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4334
4335         return 0;
4336 }
4337
4338 /*
4339  * Concurrency: @dt is write locked.
4340  */
4341 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
4342                          const char *name, struct thandle *handle)
4343 {
4344         struct osd_object      *obj    = osd_dt_obj(dt);
4345         struct inode           *inode  = obj->oo_inode;
4346         struct osd_thread_info *info   = osd_oti_get(env);
4347         struct dentry          *dentry = &info->oti_obj_dentry;
4348         int                     rc;
4349
4350         if (!dt_object_exists(dt))
4351                 return -ENOENT;
4352
4353         LASSERT(!dt_object_remote(dt));
4354         LASSERT(inode->i_op != NULL);
4355         LASSERT(inode->i_op->removexattr != NULL);
4356         LASSERT(handle != NULL);
4357
4358         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4359
4360         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4361                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
4362
4363                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
4364                                  &info->oti_ost_attrs);
4365                 if (!rc) {
4366                         LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4367
4368                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4369                         lustre_lma_swab(lma);
4370                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4371                                              sizeof(*lma), XATTR_REPLACE);
4372                         if (!rc)
4373                                 obj->oo_pfid_in_lma = 0;
4374                 }
4375         } else {
4376                 ll_vfs_dq_init(inode);
4377                 dentry->d_inode = inode;
4378                 dentry->d_sb = inode->i_sb;
4379                 rc = inode->i_op->removexattr(dentry, name);
4380         }
4381
4382         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4383
4384         if (rc == 0 &&
4385             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4386              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4387                 osd_oxc_del(obj, name);
4388
4389         return rc;
4390 }
4391
4392 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt,
4393                            __u64 start, __u64 end)
4394 {
4395         struct osd_object       *obj    = osd_dt_obj(dt);
4396         struct inode            *inode  = obj->oo_inode;
4397         struct osd_thread_info  *info   = osd_oti_get(env);
4398         struct dentry           *dentry = &info->oti_obj_dentry;
4399         struct file             *file   = &info->oti_file;
4400         int                     rc;
4401
4402         ENTRY;
4403
4404         dentry->d_inode = inode;
4405         dentry->d_sb = inode->i_sb;
4406         file->f_path.dentry = dentry;
4407         file->f_mapping = inode->i_mapping;
4408         file->f_op = inode->i_fop;
4409         set_file_inode(file, inode);
4410
4411         rc = ll_vfs_fsync_range(file, start, end, 0);
4412
4413         RETURN(rc);
4414 }
4415
4416 static int osd_invalidate(const struct lu_env *env, struct dt_object *dt)
4417 {
4418         return 0;
4419 }
4420
4421 /*
4422  * Index operations.
4423  */
4424
4425 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
4426                            const struct dt_index_features *feat)
4427 {
4428         struct iam_descr *descr;
4429
4430         if (osd_object_is_root(o))
4431                 return feat == &dt_directory_features;
4432
4433         LASSERT(o->oo_dir != NULL);
4434
4435         descr = o->oo_dir->od_container.ic_descr;
4436         if (feat == &dt_directory_features) {
4437                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
4438                         return 1;
4439                 else
4440                         return 0;
4441         } else {
4442                 return
4443                         feat->dif_keysize_min <= descr->id_key_size &&
4444                         descr->id_key_size <= feat->dif_keysize_max &&
4445                         feat->dif_recsize_min <= descr->id_rec_size &&
4446                         descr->id_rec_size <= feat->dif_recsize_max &&
4447                         !(feat->dif_flags & (DT_IND_VARKEY |
4448                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
4449                         ergo(feat->dif_flags & DT_IND_UPDATE,
4450                              1 /* XXX check that object (and file system) is
4451                                 * writable */);
4452         }
4453 }
4454
4455 static int osd_iam_container_init(const struct lu_env *env,
4456                                   struct osd_object *obj,
4457                                   struct osd_directory *dir)
4458 {
4459         struct iam_container *bag = &dir->od_container;
4460         int result;
4461
4462         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
4463         if (result != 0)
4464                 return result;
4465
4466         result = iam_container_setup(bag);
4467         if (result == 0)
4468                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
4469         else
4470                 iam_container_fini(bag);
4471
4472         return result;
4473 }
4474
4475
4476 /*
4477  * Concurrency: no external locking is necessary.
4478  */
4479 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
4480                          const struct dt_index_features *feat)
4481 {
4482         int                      result;
4483         int                      skip_iam = 0;
4484         struct osd_object       *obj = osd_dt_obj(dt);
4485
4486         LINVRNT(osd_invariant(obj));
4487
4488         if (osd_object_is_root(obj)) {
4489                 dt->do_index_ops = &osd_index_ea_ops;
4490                 result = 0;
4491         } else if (feat == &dt_directory_features) {
4492                 dt->do_index_ops = &osd_index_ea_ops;
4493                 if (obj->oo_inode == NULL || S_ISDIR(obj->oo_inode->i_mode))
4494                         result = 0;
4495                 else
4496                         result = -ENOTDIR;
4497                 skip_iam = 1;
4498         } else if (unlikely(feat == &dt_otable_features)) {
4499                 dt->do_index_ops = &osd_otable_ops;
4500                 return 0;
4501         } else if (unlikely(feat == &dt_acct_features)) {
4502                 dt->do_index_ops = &osd_acct_index_ops;
4503                 result = 0;
4504                 skip_iam = 1;
4505         } else if (!osd_has_index(obj)) {
4506                 struct osd_directory *dir;
4507                 struct osd_device *osd = osd_obj2dev(obj);
4508                 const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4509
4510                 OBD_ALLOC_PTR(dir);
4511                 if (dir) {
4512
4513                         spin_lock(&obj->oo_guard);
4514                         if (obj->oo_dir == NULL)
4515                                 obj->oo_dir = dir;
4516                         else
4517                                 /*
4518                                  * Concurrent thread allocated container data.
4519                                  */
4520                                 OBD_FREE_PTR(dir);
4521                         spin_unlock(&obj->oo_guard);
4522                         /*
4523                          * Now, that we have container data, serialize its
4524                          * initialization.
4525                          */
4526                         down_write(&obj->oo_ext_idx_sem);
4527                         /*
4528                          * recheck under lock.
4529                          */
4530
4531                         if (osd_has_index(obj)) {
4532                                 result = 0;
4533                                 goto unlock;
4534                         }
4535
4536                         result = osd_iam_container_init(env, obj, obj->oo_dir);
4537                         if (result || feat == &dt_lfsck_namespace_features ||
4538                             feat == &dt_lfsck_layout_orphan_features ||
4539                             feat == &dt_lfsck_layout_dangling_features)
4540                                 goto unlock;
4541
4542                         result = osd_index_register(osd, fid,
4543                                                     feat->dif_keysize_max,
4544                                                     feat->dif_recsize_max);
4545                         if (result < 0)
4546                                 CWARN("%s: failed to register index "
4547                                       DFID": rc = %d\n",
4548                                       osd_name(osd), PFID(fid), result);
4549                         else if (result > 0)
4550                                 result = 0;
4551                         else
4552                                 CDEBUG(D_LFSCK, "%s: index object "DFID
4553                                        " (%d/%d) registered\n",
4554                                        osd_name(osd), PFID(fid),
4555                                        (int)feat->dif_keysize_max,
4556                                        (int)feat->dif_recsize_max);
4557
4558 unlock:
4559                         up_write(&obj->oo_ext_idx_sem);
4560                 } else {
4561                         result = -ENOMEM;
4562                 }
4563         } else {
4564                 result = 0;
4565         }
4566
4567         if (result == 0 && skip_iam == 0) {
4568                 if (!osd_iam_index_probe(env, obj, feat))
4569                         result = -ENOTDIR;
4570         }
4571         LINVRNT(osd_invariant(obj));
4572
4573         return result;
4574 }
4575
4576 static int osd_otable_it_attr_get(const struct lu_env *env,
4577                                  struct dt_object *dt,
4578                                  struct lu_attr *attr)
4579 {
4580         attr->la_valid = 0;
4581         return 0;
4582 }
4583
4584 static const struct dt_object_operations osd_obj_ops = {
4585         .do_read_lock           = osd_read_lock,
4586         .do_write_lock          = osd_write_lock,
4587         .do_read_unlock         = osd_read_unlock,
4588         .do_write_unlock        = osd_write_unlock,
4589         .do_write_locked        = osd_write_locked,
4590         .do_attr_get            = osd_attr_get,
4591         .do_declare_attr_set    = osd_declare_attr_set,
4592         .do_attr_set            = osd_attr_set,
4593         .do_ah_init             = osd_ah_init,
4594         .do_declare_create      = osd_declare_create,
4595         .do_create              = osd_create,
4596         .do_declare_destroy     = osd_declare_destroy,
4597         .do_destroy             = osd_destroy,
4598         .do_index_try           = osd_index_try,
4599         .do_declare_ref_add     = osd_declare_ref_add,
4600         .do_ref_add             = osd_ref_add,
4601         .do_declare_ref_del     = osd_declare_ref_del,
4602         .do_ref_del             = osd_ref_del,
4603         .do_xattr_get           = osd_xattr_get,
4604         .do_declare_xattr_set   = osd_declare_xattr_set,
4605         .do_xattr_set           = osd_xattr_set,
4606         .do_declare_xattr_del   = osd_declare_xattr_del,
4607         .do_xattr_del           = osd_xattr_del,
4608         .do_xattr_list          = osd_xattr_list,
4609         .do_object_sync         = osd_object_sync,
4610         .do_invalidate          = osd_invalidate,
4611 };
4612
4613 static const struct dt_object_operations osd_obj_otable_it_ops = {
4614         .do_attr_get    = osd_otable_it_attr_get,
4615         .do_index_try   = osd_index_try,
4616 };
4617
4618 static int osd_index_declare_iam_delete(const struct lu_env *env,
4619                                         struct dt_object *dt,
4620                                         const struct dt_key *key,
4621                                         struct thandle *handle)
4622 {
4623         struct osd_thandle    *oh;
4624
4625         oh = container_of0(handle, struct osd_thandle, ot_super);
4626         LASSERT(oh->ot_handle == NULL);
4627
4628         /* Recycle  may cause additional three blocks to be changed. */
4629         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
4630                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
4631
4632         return 0;
4633 }
4634
4635 /**
4636  *      delete a (key, value) pair from index \a dt specified by \a key
4637  *
4638  *      \param  dt      osd index object
4639  *      \param  key     key for index
4640  *      \param  rec     record reference
4641  *      \param  handle  transaction handler
4642  *
4643  *      \retval  0  success
4644  *      \retval -ve   failure
4645  */
4646 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
4647                                 const struct dt_key *key,
4648                                 struct thandle *handle)
4649 {
4650         struct osd_thread_info *oti = osd_oti_get(env);
4651         struct osd_object      *obj = osd_dt_obj(dt);
4652         struct osd_thandle     *oh;
4653         struct iam_path_descr  *ipd;
4654         struct iam_container   *bag = &obj->oo_dir->od_container;
4655         int                     rc;
4656         ENTRY;
4657
4658         if (!dt_object_exists(dt))
4659                 RETURN(-ENOENT);
4660
4661         LINVRNT(osd_invariant(obj));
4662         LASSERT(!dt_object_remote(dt));
4663         LASSERT(bag->ic_object == obj->oo_inode);
4664         LASSERT(handle != NULL);
4665
4666         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
4667
4668         ipd = osd_idx_ipd_get(env, bag);
4669         if (unlikely(ipd == NULL))
4670                 RETURN(-ENOMEM);
4671
4672         oh = container_of0(handle, struct osd_thandle, ot_super);
4673         LASSERT(oh->ot_handle != NULL);
4674         LASSERT(oh->ot_handle->h_transaction != NULL);
4675
4676         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
4677                 /* swab quota uid/gid provided by caller */
4678                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4679                 key = (const struct dt_key *)&oti->oti_quota_id;
4680         }
4681
4682         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
4683         osd_ipd_put(env, bag, ipd);
4684         LINVRNT(osd_invariant(obj));
4685         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
4686         RETURN(rc);
4687 }
4688
4689 static int osd_index_declare_ea_delete(const struct lu_env *env,
4690                                        struct dt_object *dt,
4691                                        const struct dt_key *key,
4692                                        struct thandle *handle)
4693 {
4694         struct osd_thandle *oh;
4695         struct inode       *inode;
4696         int                 rc, credits;
4697         ENTRY;
4698
4699         LASSERT(!dt_object_remote(dt));
4700         LASSERT(handle != NULL);
4701
4702         oh = container_of0(handle, struct osd_thandle, ot_super);
4703         LASSERT(oh->ot_handle == NULL);
4704
4705         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE];
4706         osd_trans_declare_op(env, oh, OSD_OT_DELETE, credits);
4707
4708         inode = osd_dt_obj(dt)->oo_inode;
4709         if (inode == NULL)
4710                 RETURN(-ENOENT);
4711
4712         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
4713                                    i_projid_read(inode), 0, oh, osd_dt_obj(dt),
4714                                    NULL, OSD_QID_BLK);
4715         RETURN(rc);
4716 }
4717
4718 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
4719                                           struct dt_rec *fid)
4720 {
4721         struct osd_fid_pack *rec;
4722         int                  rc = -ENODATA;
4723
4724         if (de->file_type & LDISKFS_DIRENT_LUFID) {
4725                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
4726                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
4727                 if (rc == 0 && unlikely(!fid_is_sane((struct lu_fid *)fid)))
4728                         rc = -EINVAL;
4729         }
4730         return rc;
4731 }
4732
4733 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
4734                           const struct lu_fid *fid)
4735 {
4736         struct seq_server_site  *ss = osd_seq_site(osd);
4737         ENTRY;
4738
4739         /* FID seqs not in FLDB, must be local seq */
4740         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
4741                 RETURN(0);
4742
4743         /* If FLD is not being initialized yet, it only happens during the
4744          * initialization, likely during mgs initialization, and we assume
4745          * this is local FID. */
4746         if (ss == NULL || ss->ss_server_fld == NULL)
4747                 RETURN(0);
4748
4749         /* Only check the local FLDB here */
4750         if (osd_seq_exists(env, osd, fid_seq(fid)))
4751                 RETURN(0);
4752
4753         RETURN(1);
4754 }
4755
4756 static void osd_take_care_of_agent(const struct lu_env *env,
4757                                    struct osd_device *osd,
4758                                    struct osd_thandle *oh,
4759                                    struct ldiskfs_dir_entry_2 *de)
4760 {
4761         struct lu_fid *fid = &osd_oti_get(env)->oti_fid;
4762         struct osd_idmap_cache *idc;
4763         int rc, schedule = 0;
4764
4765         LASSERT(de != NULL);
4766
4767         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
4768         if (likely(rc == 0)) {
4769                 idc = osd_idc_find_or_init(env, osd, fid);
4770                 if (IS_ERR(idc) || idc->oic_remote)
4771                         schedule = 1;
4772         } else if (rc == -ENODATA) {
4773                 /* can't get FID, postpone to the end of the
4774                  * transaction when iget() is safe */
4775                 schedule = 1;
4776         } else {
4777                 CERROR("%s: can't get FID: rc = %d\n", osd_name(osd), rc);
4778         }
4779         if (schedule)
4780                 osd_schedule_agent_inode_removal(env, oh,
4781                                                  le32_to_cpu(de->inode));
4782 }
4783
4784 /**
4785  * Index delete function for interoperability mode (b11826).
4786  * It will remove the directory entry added by osd_index_ea_insert().
4787  * This entry is needed to maintain name->fid mapping.
4788  *
4789  * \param key,  key i.e. file entry to be deleted
4790  *
4791  * \retval   0, on success
4792  * \retval -ve, on error
4793  */
4794 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
4795                                const struct dt_key *key, struct thandle *handle)
4796 {
4797         struct osd_object          *obj = osd_dt_obj(dt);
4798         struct inode               *dir = obj->oo_inode;
4799         struct dentry              *dentry;
4800         struct osd_thandle         *oh;
4801         struct ldiskfs_dir_entry_2 *de = NULL;
4802         struct buffer_head         *bh;
4803         struct htree_lock          *hlock = NULL;
4804         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
4805         int                        rc;
4806         ENTRY;
4807
4808         if (!dt_object_exists(dt))
4809                 RETURN(-ENOENT);
4810
4811         LINVRNT(osd_invariant(obj));
4812         LASSERT(!dt_object_remote(dt));
4813         LASSERT(handle != NULL);
4814
4815         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
4816
4817         oh = container_of(handle, struct osd_thandle, ot_super);
4818         LASSERT(oh->ot_handle != NULL);
4819         LASSERT(oh->ot_handle->h_transaction != NULL);
4820
4821         ll_vfs_dq_init(dir);
4822         dentry = osd_child_dentry_get(env, obj,
4823                                       (char *)key, strlen((char *)key));
4824
4825         if (obj->oo_hl_head != NULL) {
4826                 hlock = osd_oti_get(env)->oti_hlock;
4827                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4828                                    dir, LDISKFS_HLOCK_DEL);
4829         } else {
4830                 down_write(&obj->oo_ext_idx_sem);
4831         }
4832
4833         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
4834         if (!IS_ERR(bh)) {
4835                 /* If this is not the ".." entry, it might be a remote DNE
4836                  * entry and  we need to check if the FID is for a remote
4837                  * MDT.  If the FID is  not in the directory entry (e.g.
4838                  * upgraded 1.8 filesystem without dirdata enabled) then
4839                  * we need to get the FID from the LMA. For a remote directory
4840                  * there HAS to be an LMA, it cannot be an IGIF inode in this
4841                  * case.
4842                  *
4843                  * Delete the entry before the agent inode in order to
4844                  * simplify error handling.  At worst an error after deleting
4845                  * the entry first might leak the agent inode afterward. The
4846                  * reverse would need filesystem abort in case of error deleting
4847                  * the entry after the agent had been removed, or leave a
4848                  * dangling entry pointing at a random inode. */
4849                 if (strcmp((char *)key, dotdot) != 0)
4850                         osd_take_care_of_agent(env, osd, oh, de);
4851                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
4852                 brelse(bh);
4853         } else {
4854                 rc = PTR_ERR(bh);
4855         }
4856         if (hlock != NULL)
4857                 ldiskfs_htree_unlock(hlock);
4858         else
4859                 up_write(&obj->oo_ext_idx_sem);
4860
4861         GOTO(out, rc);
4862
4863 out:
4864         LASSERT(osd_invariant(obj));
4865         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
4866         RETURN(rc);
4867 }
4868
4869 /**
4870  *      Lookup index for \a key and copy record to \a rec.
4871  *
4872  *      \param  dt      osd index object
4873  *      \param  key     key for index
4874  *      \param  rec     record reference
4875  *
4876  *      \retval  +ve  success : exact mach
4877  *      \retval  0    return record with key not greater than \a key
4878  *      \retval -ve   failure
4879  */
4880 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
4881                                 struct dt_rec *rec, const struct dt_key *key)
4882 {
4883         struct osd_object      *obj = osd_dt_obj(dt);
4884         struct iam_path_descr  *ipd;
4885         struct iam_container   *bag = &obj->oo_dir->od_container;
4886         struct osd_thread_info *oti = osd_oti_get(env);
4887         struct iam_iterator    *it = &oti->oti_idx_it;
4888         struct iam_rec         *iam_rec;
4889         int                     rc;
4890         ENTRY;
4891
4892         if (!dt_object_exists(dt))
4893                 RETURN(-ENOENT);
4894
4895         LASSERT(osd_invariant(obj));
4896         LASSERT(!dt_object_remote(dt));
4897         LASSERT(bag->ic_object == obj->oo_inode);
4898
4899         ipd = osd_idx_ipd_get(env, bag);
4900         if (IS_ERR(ipd))
4901                 RETURN(-ENOMEM);
4902
4903         /* got ipd now we can start iterator. */
4904         iam_it_init(it, bag, 0, ipd);
4905
4906         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
4907                 /* swab quota uid/gid provided by caller */
4908                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4909                 key = (const struct dt_key *)&oti->oti_quota_id;
4910         }
4911
4912         rc = iam_it_get(it, (struct iam_key *)key);
4913         if (rc >= 0) {
4914                 if (S_ISDIR(obj->oo_inode->i_mode))
4915                         iam_rec = (struct iam_rec *)oti->oti_ldp;
4916                 else
4917                         iam_rec = (struct iam_rec *) rec;
4918
4919                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
4920
4921                 if (S_ISDIR(obj->oo_inode->i_mode))
4922                         osd_fid_unpack((struct lu_fid *) rec,
4923                                        (struct osd_fid_pack *)iam_rec);
4924                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
4925                         osd_quota_unpack(obj, rec);
4926         }
4927
4928         iam_it_put(it);
4929         iam_it_fini(it);
4930         osd_ipd_put(env, bag, ipd);
4931
4932         LINVRNT(osd_invariant(obj));
4933
4934         RETURN(rc);
4935 }
4936
4937 static int osd_index_declare_iam_insert(const struct lu_env *env,
4938                                         struct dt_object *dt,
4939                                         const struct dt_rec *rec,
4940                                         const struct dt_key *key,
4941                                         struct thandle *handle)
4942 {
4943         struct osd_thandle *oh;
4944
4945         LASSERT(handle != NULL);
4946
4947         oh = container_of0(handle, struct osd_thandle, ot_super);
4948         LASSERT(oh->ot_handle == NULL);
4949
4950         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4951                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4952
4953         return 0;
4954 }
4955
4956 /**
4957  *      Inserts (key, value) pair in \a dt index object.
4958  *
4959  *      \param  dt      osd index object
4960  *      \param  key     key for index
4961  *      \param  rec     record reference
4962  *      \param  th      transaction handler
4963  *
4964  *      \retval  0  success
4965  *      \retval -ve failure
4966  */
4967 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
4968                                 const struct dt_rec *rec,
4969                                 const struct dt_key *key, struct thandle *th,
4970                                 int ignore_quota)
4971 {
4972         struct osd_object     *obj = osd_dt_obj(dt);
4973         struct iam_path_descr *ipd;
4974         struct osd_thandle    *oh;
4975         struct iam_container  *bag;
4976         struct osd_thread_info *oti = osd_oti_get(env);
4977         struct iam_rec         *iam_rec;
4978         int                     rc;
4979         ENTRY;
4980
4981         if (!dt_object_exists(dt))
4982                 RETURN(-ENOENT);
4983
4984         LINVRNT(osd_invariant(obj));
4985         LASSERT(!dt_object_remote(dt));
4986
4987         bag = &obj->oo_dir->od_container;
4988         LASSERT(bag->ic_object == obj->oo_inode);
4989         LASSERT(th != NULL);
4990
4991         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4992
4993         ipd = osd_idx_ipd_get(env, bag);
4994         if (unlikely(ipd == NULL))
4995                 RETURN(-ENOMEM);
4996
4997         oh = container_of0(th, struct osd_thandle, ot_super);
4998         LASSERT(oh->ot_handle != NULL);
4999         LASSERT(oh->ot_handle->h_transaction != NULL);
5000         if (S_ISDIR(obj->oo_inode->i_mode)) {
5001                 iam_rec = (struct iam_rec *)oti->oti_ldp;
5002                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
5003         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5004                 /* pack quota uid/gid */
5005                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5006                 key = (const struct dt_key *)&oti->oti_quota_id;
5007                 /* pack quota record */
5008                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
5009                 iam_rec = (struct iam_rec *)rec;
5010         } else {
5011                 iam_rec = (struct iam_rec *)rec;
5012         }
5013
5014         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
5015                         iam_rec, ipd);
5016         osd_ipd_put(env, bag, ipd);
5017         LINVRNT(osd_invariant(obj));
5018         osd_trans_exec_check(env, th, OSD_OT_INSERT);
5019         RETURN(rc);
5020 }
5021
5022 /**
5023  * Calls ldiskfs_add_entry() to add directory entry
5024  * into the directory. This is required for
5025  * interoperability mode (b11826)
5026  *
5027  * \retval   0, on success
5028  * \retval -ve, on error
5029  */
5030 static int __osd_ea_add_rec(struct osd_thread_info *info,
5031                             struct osd_object *pobj, struct inode  *cinode,
5032                             const char *name, const struct lu_fid *fid,
5033                             struct htree_lock *hlock, struct thandle *th)
5034 {
5035         struct ldiskfs_dentry_param *ldp;
5036         struct dentry               *child;
5037         struct osd_thandle          *oth;
5038         int                          rc;
5039
5040         oth = container_of(th, struct osd_thandle, ot_super);
5041         LASSERT(oth->ot_handle != NULL);
5042         LASSERT(oth->ot_handle->h_transaction != NULL);
5043         LASSERT(pobj->oo_inode);
5044
5045         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
5046         if (unlikely(pobj->oo_inode ==
5047                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
5048                 ldp->edp_magic = 0;
5049         else
5050                 osd_get_ldiskfs_dirent_param(ldp, fid);
5051         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
5052         child->d_fsdata = (void *)ldp;
5053         ll_vfs_dq_init(pobj->oo_inode);
5054         rc = osd_ldiskfs_add_entry(info, osd_obj2dev(pobj), oth->ot_handle,
5055                                    child, cinode, hlock);
5056         if (rc == 0 && OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_TYPE)) {
5057                 struct ldiskfs_dir_entry_2      *de;
5058                 struct buffer_head              *bh;
5059                 int                              rc1;
5060
5061                 bh = osd_ldiskfs_find_entry(pobj->oo_inode, &child->d_name, &de,
5062                                             NULL, hlock);
5063                 if (!IS_ERR(bh)) {
5064                         rc1 = ldiskfs_journal_get_write_access(oth->ot_handle,
5065                                                                bh);
5066                         if (rc1 == 0) {
5067                                 if (S_ISDIR(cinode->i_mode))
5068                                         de->file_type = LDISKFS_DIRENT_LUFID |
5069                                                         LDISKFS_FT_REG_FILE;
5070                                 else
5071                                         de->file_type = LDISKFS_DIRENT_LUFID |
5072                                                         LDISKFS_FT_DIR;
5073                                 ldiskfs_handle_dirty_metadata(oth->ot_handle,
5074                                                               NULL, bh);
5075                         }
5076                         brelse(bh);
5077                 }
5078         }
5079
5080         RETURN(rc);
5081 }
5082
5083 /**
5084  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
5085  * into the directory.Also sets flags into osd object to
5086  * indicate dot and dotdot are created. This is required for
5087  * interoperability mode (b11826)
5088  *
5089  * \param dir   directory for dot and dotdot fixup.
5090  * \param obj   child object for linking
5091  *
5092  * \retval   0, on success
5093  * \retval -ve, on error
5094  */
5095 static int osd_add_dot_dotdot(struct osd_thread_info *info,
5096                               struct osd_object *dir,
5097                               struct inode *parent_dir, const char *name,
5098                               const struct lu_fid *dot_fid,
5099                               const struct lu_fid *dot_dot_fid,
5100                               struct thandle *th)
5101 {
5102         struct inode                *inode = dir->oo_inode;
5103         struct osd_thandle          *oth;
5104         int result = 0;
5105
5106         oth = container_of(th, struct osd_thandle, ot_super);
5107         LASSERT(oth->ot_handle->h_transaction != NULL);
5108         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
5109
5110         if (strcmp(name, dot) == 0) {
5111                 if (dir->oo_compat_dot_created) {
5112                         result = -EEXIST;
5113                 } else {
5114                         LASSERT(inode->i_ino == parent_dir->i_ino);
5115                         dir->oo_compat_dot_created = 1;
5116                         result = 0;
5117                 }
5118         } else if (strcmp(name, dotdot) == 0) {
5119                 if (!dir->oo_compat_dot_created)
5120                         return -EINVAL;
5121                 /* in case of rename, dotdot is already created */
5122                 if (dir->oo_compat_dotdot_created) {
5123                         return __osd_ea_add_rec(info, dir, parent_dir, name,
5124                                                 dot_dot_fid, NULL, th);
5125                 }
5126
5127                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
5128                         struct lu_fid tfid = *dot_dot_fid;
5129
5130                         tfid.f_oid--;
5131                         result = osd_add_dot_dotdot_internal(info,
5132                                         dir->oo_inode, parent_dir, dot_fid,
5133                                         &tfid, oth);
5134                 } else {
5135                         result = osd_add_dot_dotdot_internal(info,
5136                                         dir->oo_inode, parent_dir, dot_fid,
5137                                         dot_dot_fid, oth);
5138                 }
5139
5140                 if (result == 0)
5141                         dir->oo_compat_dotdot_created = 1;
5142         }
5143
5144         return result;
5145 }
5146
5147
5148 /**
5149  * It will call the appropriate osd_add* function and return the
5150  * value, return by respective functions.
5151  */
5152 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
5153                           struct inode *cinode, const char *name,
5154                           const struct lu_fid *fid, struct thandle *th)
5155 {
5156         struct osd_thread_info *info   = osd_oti_get(env);
5157         struct htree_lock      *hlock;
5158         int                     rc;
5159
5160         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
5161
5162         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
5163                                                    name[2] =='\0'))) {
5164                 if (hlock != NULL) {
5165                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5166                                            pobj->oo_inode, 0);
5167                 } else {
5168                         down_write(&pobj->oo_ext_idx_sem);
5169                 }
5170
5171                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
5172                                         lu_object_fid(&pobj->oo_dt.do_lu),
5173                                         fid, th);
5174         } else {
5175                 if (hlock != NULL) {
5176                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5177                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
5178                 } else {
5179                         down_write(&pobj->oo_ext_idx_sem);
5180                 }
5181
5182                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
5183                         struct lu_fid *tfid = &info->oti_fid;
5184
5185                         *tfid = *fid;
5186                         tfid->f_ver = ~0;
5187                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
5188                                               tfid, hlock, th);
5189                 } else {
5190                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
5191                                               hlock, th);
5192                 }
5193         }
5194         if (hlock != NULL)
5195                 ldiskfs_htree_unlock(hlock);
5196         else
5197                 up_write(&pobj->oo_ext_idx_sem);
5198
5199         return rc;
5200 }
5201
5202 static int
5203 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
5204                       struct osd_idmap_cache *oic)
5205 {
5206         struct lustre_scrub *scrub = &dev->od_scrub.os_scrub;
5207         struct lu_fid *fid = &oic->oic_fid;
5208         struct osd_inode_id *id = &oic->oic_lid;
5209         struct inode *inode = NULL;
5210         int once = 0;
5211         bool insert;
5212         int rc;
5213         ENTRY;
5214
5215         if (!fid_is_norm(fid) && !fid_is_igif(fid))
5216                 RETURN(0);
5217
5218         if (thread_is_running(&scrub->os_thread) &&
5219             scrub->os_pos_current > id->oii_ino)
5220                 RETURN(0);
5221
5222         if (dev->od_auto_scrub_interval == AS_NEVER ||
5223             cfs_time_before(ktime_get_real_seconds(),
5224                             scrub->os_file.sf_time_last_complete +
5225                             dev->od_auto_scrub_interval))
5226                 RETURN(0);
5227
5228 again:
5229         rc = osd_oi_lookup(oti, dev, fid, &oti->oti_id, 0);
5230         if (rc == -ENOENT) {
5231                 __u32 gen = id->oii_gen;
5232
5233                 insert = true;
5234                 if (inode != NULL)
5235                         goto trigger;
5236
5237                 inode = osd_iget(oti, dev, id);
5238                 /* The inode has been removed (by race maybe). */
5239                 if (IS_ERR(inode)) {
5240                         rc = PTR_ERR(inode);
5241
5242                         RETURN(rc == -ESTALE ? -ENOENT : rc);
5243                 }
5244
5245                 /* The OI mapping is lost. */
5246                 if (gen != OSD_OII_NOGEN)
5247                         goto trigger;
5248
5249                 /* The inode may has been reused by others, we do not know,
5250                  * leave it to be handled by subsequent osd_fid_lookup(). */
5251                 GOTO(out, rc = 0);
5252         } else if (rc || osd_id_eq(id, &oti->oti_id)) {
5253                 GOTO(out, rc);
5254         }
5255
5256         insert = false;
5257
5258 trigger:
5259         if (thread_is_running(&scrub->os_thread)) {
5260                 if (inode == NULL) {
5261                         inode = osd_iget(oti, dev, id);
5262                         /* The inode has been removed (by race maybe). */
5263                         if (IS_ERR(inode)) {
5264                                 rc = PTR_ERR(inode);
5265
5266                                 RETURN(rc == -ESTALE ? -ENOENT : rc);
5267                         }
5268                 }
5269
5270                 rc = osd_oii_insert(dev, oic, insert);
5271                 /* There is race condition between osd_oi_lookup and OI scrub.
5272                  * The OI scrub finished just after osd_oi_lookup() failure.
5273                  * Under such case, it is unnecessary to trigger OI scrub again,
5274                  * but try to call osd_oi_lookup() again. */
5275                 if (unlikely(rc == -EAGAIN))
5276                         goto again;
5277
5278                 if (!S_ISDIR(inode->i_mode))
5279                         rc = 0;
5280                 else
5281                         rc = osd_check_lmv(oti, dev, inode, oic);
5282
5283                 GOTO(out, rc);
5284         }
5285
5286         if (dev->od_auto_scrub_interval != AS_NEVER && ++once == 1) {
5287                 rc = osd_scrub_start(oti->oti_env, dev, SS_AUTO_PARTIAL |
5288                                      SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT);
5289                 CDEBUG(D_LFSCK | D_CONSOLE | D_WARNING,
5290                        "%s: trigger partial OI scrub for RPC inconsistency "
5291                        "checking FID "DFID": rc = %d\n",
5292                        osd_dev2name(dev), PFID(fid), rc);
5293                 if (rc == 0 || rc == -EALREADY)
5294                         goto again;
5295         }
5296
5297         GOTO(out, rc);
5298
5299 out:
5300         if (inode)
5301                 iput(inode);
5302
5303         RETURN(rc);
5304 }
5305
5306 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
5307                                struct osd_device *dev,
5308                                struct osd_idmap_cache *oic,
5309                                struct lu_fid *fid, __u32 ino)
5310 {
5311         struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
5312         struct inode *inode;
5313         int rc;
5314
5315         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
5316         inode = osd_iget(oti, dev, &oic->oic_lid);
5317         if (IS_ERR(inode)) {
5318                 fid_zero(&oic->oic_fid);
5319                 return PTR_ERR(inode);
5320         }
5321
5322         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, loa);
5323         iput(inode);
5324         if (rc != 0)
5325                 fid_zero(&oic->oic_fid);
5326         else
5327                 *fid = oic->oic_fid = loa->loa_lma.lma_self_fid;
5328         return rc;
5329 }
5330
5331 void osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
5332                       struct osd_inode_id *id, const struct lu_fid *fid)
5333 {
5334         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
5335                id->oii_ino, id->oii_gen, info);
5336         info->oti_cache.oic_lid = *id;
5337         info->oti_cache.oic_fid = *fid;
5338         info->oti_cache.oic_dev = osd;
5339 }
5340
5341 /**
5342  * Get parent FID from the linkEA.
5343  *
5344  * For a directory which parent resides on remote MDT, to satisfy the
5345  * local e2fsck, we insert it into the /REMOTE_PARENT_DIR locally. On
5346  * the other hand, to make the lookup(..) on the directory can return
5347  * the real parent FID, we append the real parent FID after its ".."
5348  * name entry in the /REMOTE_PARENT_DIR.
5349  *
5350  * Unfortunately, such PFID-in-dirent cannot be preserved via file-level
5351  * backup. So after the restore, we cannot get the right parent FID from
5352  * its ".." name entry in the /REMOTE_PARENT_DIR. Under such case, since
5353  * we have stored the real parent FID in the directory object's linkEA,
5354  * we can parse the linkEA for the real parent FID.
5355  *
5356  * \param[in] env       pointer to the thread context
5357  * \param[in] obj       pointer to the object to be handled
5358  * \param[out]fid       pointer to the buffer to hold the parent FID
5359  *
5360  * \retval              0 for getting the real parent FID successfully
5361  * \retval              negative error number on failure
5362  */
5363 static int osd_get_pfid_from_linkea(const struct lu_env *env,
5364                                     struct osd_object *obj,
5365                                     struct lu_fid *fid)
5366 {
5367         struct osd_thread_info  *oti    = osd_oti_get(env);
5368         struct lu_buf           *buf    = &oti->oti_big_buf;
5369         struct dentry           *dentry = &oti->oti_obj_dentry;
5370         struct inode            *inode  = obj->oo_inode;
5371         struct linkea_data       ldata  = { NULL };
5372         int                      rc;
5373         ENTRY;
5374
5375         fid_zero(fid);
5376         if (!S_ISDIR(inode->i_mode))
5377                 RETURN(-EIO);
5378
5379 again:
5380         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5381                              buf->lb_buf, buf->lb_len);
5382         if (rc == -ERANGE) {
5383                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5384                                      NULL, 0);
5385                 if (rc > 0) {
5386                         lu_buf_realloc(buf, rc);
5387                         if (buf->lb_buf == NULL)
5388                                 RETURN(-ENOMEM);
5389
5390                         goto again;
5391                 }
5392         }
5393
5394         if (unlikely(rc == 0))
5395                 RETURN(-ENODATA);
5396
5397         if (rc < 0)
5398                 RETURN(rc);
5399
5400         if (unlikely(buf->lb_buf == NULL)) {
5401                 lu_buf_realloc(buf, rc);
5402                 if (buf->lb_buf == NULL)
5403                         RETURN(-ENOMEM);
5404
5405                 goto again;
5406         }
5407
5408         ldata.ld_buf = buf;
5409         rc = linkea_init_with_rec(&ldata);
5410         if (!rc) {
5411                 linkea_first_entry(&ldata);
5412                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, NULL, fid);
5413         }
5414
5415         RETURN(rc);
5416 }
5417
5418 static int osd_verify_ent_by_linkea(const struct lu_env *env,
5419                                     struct inode *inode,
5420                                     const struct lu_fid *pfid,
5421                                     const char *name, const int namelen)
5422 {
5423         struct osd_thread_info *oti = osd_oti_get(env);
5424         struct lu_buf *buf = &oti->oti_big_buf;
5425         struct dentry *dentry = &oti->oti_obj_dentry;
5426         struct linkea_data ldata = { NULL };
5427         struct lu_name cname = { .ln_name = name,
5428                                  .ln_namelen = namelen };
5429         int rc;
5430         ENTRY;
5431
5432 again:
5433         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5434                              buf->lb_buf, buf->lb_len);
5435         if (rc == -ERANGE)
5436                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK, NULL, 0);
5437
5438         if (rc < 0)
5439                 RETURN(rc);
5440
5441         if (unlikely(rc == 0))
5442                 RETURN(-ENODATA);
5443
5444         if (buf->lb_len < rc) {
5445                 lu_buf_realloc(buf, rc);
5446                 if (buf->lb_buf == NULL)
5447                         RETURN(-ENOMEM);
5448
5449                 goto again;
5450         }
5451
5452         ldata.ld_buf = buf;
5453         rc = linkea_init_with_rec(&ldata);
5454         if (!rc)
5455                 rc = linkea_links_find(&ldata, &cname, pfid);
5456
5457         RETURN(rc);
5458 }
5459
5460 /**
5461  * Calls ->lookup() to find dentry. From dentry get inode and
5462  * read inode's ea to get fid. This is required for  interoperability
5463  * mode (b11826)
5464  *
5465  * \retval   0, on success
5466  * \retval -ve, on error
5467  */
5468 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
5469                              struct dt_rec *rec, const struct dt_key *key)
5470 {
5471         struct inode                    *dir    = obj->oo_inode;
5472         struct dentry                   *dentry;
5473         struct ldiskfs_dir_entry_2      *de;
5474         struct buffer_head              *bh;
5475         struct lu_fid                   *fid = (struct lu_fid *) rec;
5476         struct htree_lock               *hlock = NULL;
5477         int                             ino;
5478         int                             rc;
5479         ENTRY;
5480
5481         LASSERT(dir->i_op != NULL);
5482         LASSERT(dir->i_op->lookup != NULL);
5483
5484         dentry = osd_child_dentry_get(env, obj,
5485                                       (char *)key, strlen((char *)key));
5486
5487         if (obj->oo_hl_head != NULL) {
5488                 hlock = osd_oti_get(env)->oti_hlock;
5489                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5490                                    dir, LDISKFS_HLOCK_LOOKUP);
5491         } else {
5492                 down_read(&obj->oo_ext_idx_sem);
5493         }
5494
5495         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5496         if (!IS_ERR(bh)) {
5497                 struct osd_thread_info *oti = osd_oti_get(env);
5498                 struct osd_inode_id *id = &oti->oti_id;
5499                 struct osd_idmap_cache *oic = &oti->oti_cache;
5500                 struct osd_device *dev = osd_obj2dev(obj);
5501
5502                 ino = le32_to_cpu(de->inode);
5503                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
5504                         brelse(bh);
5505                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
5506                         GOTO(out, rc);
5507                 }
5508
5509                 rc = osd_get_fid_from_dentry(de, rec);
5510
5511                 /* done with de, release bh */
5512                 brelse(bh);
5513                 if (rc != 0) {
5514                         if (unlikely(ino == osd_remote_parent_ino(dev))) {
5515                                 const char *name = (const char *)key;
5516
5517                                 /* If the parent is on remote MDT, and there
5518                                  * is no FID-in-dirent, then we have to get
5519                                  * the parent FID from the linkEA.  */
5520                                 if (likely(strlen(name) == 2 &&
5521                                            name[0] == '.' && name[1] == '.'))
5522                                         rc = osd_get_pfid_from_linkea(env, obj,
5523                                                                       fid);
5524                         } else {
5525                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
5526                         }
5527                 } else {
5528                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5529                 }
5530
5531                 if (rc != 0 || osd_remote_fid(env, dev, fid)) {
5532                         fid_zero(&oic->oic_fid);
5533
5534                         GOTO(out, rc);
5535                 }
5536
5537                 osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id, fid);
5538                 rc = osd_consistency_check(oti, dev, oic);
5539                 if (rc == -ENOENT)
5540                         fid_zero(&oic->oic_fid);
5541                 else
5542                         /* Other error should not affect lookup result. */
5543                         rc = 0;
5544         } else {
5545                 rc = PTR_ERR(bh);
5546         }
5547
5548         GOTO(out, rc);
5549
5550 out:
5551         if (hlock != NULL)
5552                 ldiskfs_htree_unlock(hlock);
5553         else
5554                 up_read(&obj->oo_ext_idx_sem);
5555         return rc;
5556 }
5557
5558 static int osd_index_declare_ea_insert(const struct lu_env *env,
5559                                        struct dt_object *dt,
5560                                        const struct dt_rec *rec,
5561                                        const struct dt_key *key,
5562                                        struct thandle *handle)
5563 {
5564         struct osd_thandle      *oh;
5565         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
5566         struct dt_insert_rec    *rec1   = (struct dt_insert_rec *)rec;
5567         const struct lu_fid     *fid    = rec1->rec_fid;
5568         int                      credits, rc = 0;
5569         struct osd_idmap_cache  *idc;
5570         ENTRY;
5571
5572         LASSERT(!dt_object_remote(dt));
5573         LASSERT(handle != NULL);
5574         LASSERT(fid != NULL);
5575         LASSERT(rec1->rec_type != 0);
5576
5577         oh = container_of0(handle, struct osd_thandle, ot_super);
5578         LASSERT(oh->ot_handle == NULL);
5579
5580         credits = osd_dto_credits_noquota[DTO_INDEX_INSERT];
5581
5582         /* we can't call iget() while a transactions is running
5583          * (this can lead to a deadlock), but we need to know
5584          * inum and object type. so we find this information at
5585          * declaration and cache in per-thread info */
5586         idc = osd_idc_find_or_init(env, osd, fid);
5587         if (IS_ERR(idc))
5588                 RETURN(PTR_ERR(idc));
5589         if (idc->oic_remote) {
5590                 /* a reference to remote inode is represented by an
5591                  * agent inode which we have to create */
5592                 credits += osd_dto_credits_noquota[DTO_OBJECT_CREATE];
5593                 credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
5594         }
5595
5596         osd_trans_declare_op(env, oh, OSD_OT_INSERT, credits);
5597
5598         if (osd_dt_obj(dt)->oo_inode != NULL) {
5599                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
5600
5601                 /* We ignore block quota on meta pool (MDTs), so needn't
5602                  * calculate how many blocks will be consumed by this index
5603                  * insert */
5604                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
5605                                            i_gid_read(inode),
5606                                            i_projid_read(inode), 0,
5607                                            oh, osd_dt_obj(dt), NULL,
5608                                            OSD_QID_BLK);
5609                 if (rc)
5610                         RETURN(rc);
5611
5612 #ifdef HAVE_PROJECT_QUOTA
5613                 /* Reserve credits for local agent inode to transfer
5614                  * to 0, quota enforcement is ignored in this case.
5615                  */
5616                 if (idc->oic_remote &&
5617                     LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
5618                     i_projid_read(inode) != 0)
5619                         rc = osd_declare_attr_qid(env, osd_dt_obj(dt), oh,
5620                                                   0, i_projid_read(inode),
5621                                                   0, false, PRJQUOTA);
5622 #endif
5623         }
5624
5625
5626         RETURN(rc);
5627 }
5628
5629 /**
5630  * Index add function for interoperability mode (b11826).
5631  * It will add the directory entry.This entry is needed to
5632  * maintain name->fid mapping.
5633  *
5634  * \param key it is key i.e. file entry to be inserted
5635  * \param rec it is value of given key i.e. fid
5636  *
5637  * \retval   0, on success
5638  * \retval -ve, on error
5639  */
5640 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
5641                                const struct dt_rec *rec,
5642                                const struct dt_key *key, struct thandle *th,
5643                                int ignore_quota)
5644 {
5645         struct osd_object       *obj = osd_dt_obj(dt);
5646         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
5647         struct dt_insert_rec    *rec1   = (struct dt_insert_rec *)rec;
5648         const struct lu_fid     *fid    = rec1->rec_fid;
5649         const char              *name = (const char *)key;
5650         struct osd_thread_info  *oti   = osd_oti_get(env);
5651         struct inode            *child_inode = NULL;
5652         struct osd_idmap_cache  *idc;
5653         int                     rc;
5654         ENTRY;
5655
5656         if (!dt_object_exists(dt))
5657                 RETURN(-ENOENT);
5658
5659         LASSERT(osd_invariant(obj));
5660         LASSERT(!dt_object_remote(dt));
5661         LASSERT(th != NULL);
5662
5663         osd_trans_exec_op(env, th, OSD_OT_INSERT);
5664
5665         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!\n", PFID(fid));
5666
5667         idc = osd_idc_find(env, osd, fid);
5668         if (unlikely(idc == NULL)) {
5669                 /* this dt_insert() wasn't declared properly, so
5670                  * FID is missing in OI cache. we better do not
5671                  * lookup FID in FLDB/OI and don't risk to deadlock,
5672                  * but in some special cases (lfsck testing, etc)
5673                  * it's much simpler than fixing a caller */
5674                 CERROR("%s: "DFID" wasn't declared for insert\n",
5675                        osd_name(osd), PFID(fid));
5676                 dump_stack();
5677                 idc = osd_idc_find_or_init(env, osd, fid);
5678                 if (IS_ERR(idc))
5679                         RETURN(PTR_ERR(idc));
5680         }
5681
5682         if (idc->oic_remote) {
5683                 /* Insert remote entry */
5684                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
5685                         child_inode =
5686                         igrab(osd->od_mdt_map->omm_remote_parent->d_inode);
5687                 } else {
5688                         child_inode = osd_create_local_agent_inode(env, osd,
5689                                         obj, fid, rec1->rec_type & S_IFMT, th);
5690                         if (IS_ERR(child_inode))
5691                                 RETURN(PTR_ERR(child_inode));
5692                 }
5693         } else {
5694                 /* Insert local entry */
5695                 if (unlikely(idc->oic_lid.oii_ino == 0)) {
5696                         /* for a reason OI cache wasn't filled properly */
5697                         CERROR("%s: OIC for "DFID" isn't filled\n",
5698                                osd_name(osd), PFID(fid));
5699                         RETURN(-EINVAL);
5700                 }
5701                 child_inode = oti->oti_inode;
5702                 if (unlikely(child_inode == NULL)) {
5703                         struct ldiskfs_inode_info *lii;
5704                         OBD_ALLOC_PTR(lii);
5705                         if (lii == NULL)
5706                                 RETURN(-ENOMEM);
5707                         child_inode = oti->oti_inode = &lii->vfs_inode;
5708                 }
5709                 child_inode->i_sb = osd_sb(osd);
5710                 child_inode->i_ino = idc->oic_lid.oii_ino;
5711                 child_inode->i_mode = rec1->rec_type & S_IFMT;
5712         }
5713
5714         rc = osd_ea_add_rec(env, obj, child_inode, name, fid, th);
5715
5716         CDEBUG(D_INODE, "parent %lu insert %s:%lu rc = %d\n",
5717                obj->oo_inode->i_ino, name, child_inode->i_ino, rc);
5718
5719         if (child_inode && child_inode != oti->oti_inode)
5720                 iput(child_inode);
5721         LASSERT(osd_invariant(obj));
5722         osd_trans_exec_check(env, th, OSD_OT_INSERT);
5723         RETURN(rc);
5724 }
5725
5726 /**
5727  *  Initialize osd Iterator for given osd index object.
5728  *
5729  *  \param  dt      osd index object
5730  */
5731
5732 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
5733                                      struct dt_object *dt,
5734                                      __u32 unused)
5735 {
5736         struct osd_it_iam      *it;
5737         struct osd_object      *obj = osd_dt_obj(dt);
5738         struct lu_object       *lo  = &dt->do_lu;
5739         struct iam_path_descr  *ipd;
5740         struct iam_container   *bag = &obj->oo_dir->od_container;
5741
5742         if (!dt_object_exists(dt))
5743                 return ERR_PTR(-ENOENT);
5744
5745         OBD_ALLOC_PTR(it);
5746         if (it == NULL)
5747                 return ERR_PTR(-ENOMEM);
5748
5749         ipd = osd_it_ipd_get(env, bag);
5750         if (likely(ipd != NULL)) {
5751                 it->oi_obj = obj;
5752                 it->oi_ipd = ipd;
5753                 lu_object_get(lo);
5754                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
5755                 return (struct dt_it *)it;
5756         } else {
5757                 OBD_FREE_PTR(it);
5758                 return ERR_PTR(-ENOMEM);
5759         }
5760 }
5761
5762 /**
5763  * free given Iterator.
5764  */
5765 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
5766 {
5767         struct osd_it_iam       *it  = (struct osd_it_iam *)di;
5768         struct osd_object       *obj = it->oi_obj;
5769
5770         iam_it_fini(&it->oi_it);
5771         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
5772         osd_object_put(env, obj);
5773         OBD_FREE_PTR(it);
5774 }
5775
5776 /**
5777  *  Move Iterator to record specified by \a key
5778  *
5779  *  \param  di      osd iterator
5780  *  \param  key     key for index
5781  *
5782  *  \retval +ve  di points to record with least key not larger than key
5783  *  \retval  0   di points to exact matched key
5784  *  \retval -ve  failure
5785  */
5786
5787 static int osd_it_iam_get(const struct lu_env *env,
5788                           struct dt_it *di, const struct dt_key *key)
5789 {
5790         struct osd_thread_info  *oti = osd_oti_get(env);
5791         struct osd_it_iam       *it = (struct osd_it_iam *)di;
5792
5793         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
5794                 /* swab quota uid/gid */
5795                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5796                 key = (struct dt_key *)&oti->oti_quota_id;
5797         }
5798
5799         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
5800 }
5801
5802 /**
5803  *  Release Iterator
5804  *
5805  *  \param  di      osd iterator
5806  */
5807 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
5808 {
5809         struct osd_it_iam *it = (struct osd_it_iam *)di;
5810
5811         iam_it_put(&it->oi_it);
5812 }
5813
5814 /**
5815  *  Move iterator by one record
5816  *
5817  *  \param  di      osd iterator
5818  *
5819  *  \retval +1   end of container reached
5820  *  \retval  0   success
5821  *  \retval -ve  failure
5822  */
5823
5824 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
5825 {
5826         struct osd_it_iam *it = (struct osd_it_iam *)di;
5827
5828         return iam_it_next(&it->oi_it);
5829 }
5830
5831 /**
5832  * Return pointer to the key under iterator.
5833  */
5834
5835 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
5836                                  const struct dt_it *di)
5837 {
5838         struct osd_thread_info *oti = osd_oti_get(env);
5839         struct osd_it_iam      *it = (struct osd_it_iam *)di;
5840         struct osd_object      *obj = it->oi_obj;
5841         struct dt_key          *key;
5842
5843         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
5844
5845         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
5846                 /* swab quota uid/gid */
5847                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
5848                 key = (struct dt_key *)&oti->oti_quota_id;
5849         }
5850
5851         return key;
5852 }
5853
5854 /**
5855  * Return size of key under iterator (in bytes)
5856  */
5857
5858 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
5859 {
5860         struct osd_it_iam *it = (struct osd_it_iam *)di;
5861
5862         return iam_it_key_size(&it->oi_it);
5863 }
5864
5865 static inline void
5866 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
5867 {
5868         /* check if file type is required */
5869         if (ent->lde_attrs & LUDA_TYPE) {
5870                 struct luda_type *lt;
5871                 int align = sizeof(*lt) - 1;
5872
5873                 len = (len + align) & ~align;
5874                 lt = (struct luda_type *)(ent->lde_name + len);
5875                 lt->lt_type = cpu_to_le16(DTTOIF(type));
5876         }
5877
5878         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
5879 }
5880
5881 /**
5882  * build lu direct from backend fs dirent.
5883  */
5884
5885 static inline void
5886 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
5887                    char *name, __u16 namelen, __u16 type, __u32 attr)
5888 {
5889         ent->lde_attrs = attr | LUDA_FID;
5890         fid_cpu_to_le(&ent->lde_fid, fid);
5891
5892         ent->lde_hash = cpu_to_le64(offset);
5893         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
5894
5895         strncpy(ent->lde_name, name, namelen);
5896         ent->lde_name[namelen] = '\0';
5897         ent->lde_namelen = cpu_to_le16(namelen);
5898
5899         /* append lustre attributes */
5900         osd_it_append_attrs(ent, namelen, type);
5901 }
5902
5903 /**
5904  * Return pointer to the record under iterator.
5905  */
5906 static int osd_it_iam_rec(const struct lu_env *env,
5907                           const struct dt_it *di,
5908                           struct dt_rec *dtrec, __u32 attr)
5909 {
5910         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
5911         struct osd_thread_info *info = osd_oti_get(env);
5912         ENTRY;
5913
5914         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
5915                 const struct osd_fid_pack *rec;
5916                 struct lu_fid             *fid = &info->oti_fid;
5917                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
5918                 char                      *name;
5919                 int                        namelen;
5920                 __u64                      hash;
5921                 int                        rc;
5922
5923                 name = (char *)iam_it_key_get(&it->oi_it);
5924                 if (IS_ERR(name))
5925                         RETURN(PTR_ERR(name));
5926
5927                 namelen = iam_it_key_size(&it->oi_it);
5928
5929                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
5930                 if (IS_ERR(rec))
5931                         RETURN(PTR_ERR(rec));
5932
5933                 rc = osd_fid_unpack(fid, rec);
5934                 if (rc)
5935                         RETURN(rc);
5936
5937                 hash = iam_it_store(&it->oi_it);
5938
5939                 /* IAM does not store object type in IAM index (dir) */
5940                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
5941                                    0, LUDA_FID);
5942         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
5943                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
5944                            (struct iam_rec *)dtrec);
5945                 osd_quota_unpack(it->oi_obj, dtrec);
5946         } else {
5947                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
5948                            (struct iam_rec *)dtrec);
5949         }
5950
5951         RETURN(0);
5952 }
5953
5954 /**
5955  * Returns cookie for current Iterator position.
5956  */
5957 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
5958 {
5959         struct osd_it_iam *it = (struct osd_it_iam *)di;
5960
5961         return iam_it_store(&it->oi_it);
5962 }
5963
5964 /**
5965  * Restore iterator from cookie.
5966  *
5967  * \param  di      osd iterator
5968  * \param  hash    Iterator location cookie
5969  *
5970  * \retval +ve  di points to record with least key not larger than key.
5971  * \retval  0   di points to exact matched key
5972  * \retval -ve  failure
5973  */
5974
5975 static int osd_it_iam_load(const struct lu_env *env,
5976                            const struct dt_it *di, __u64 hash)
5977 {
5978         struct osd_it_iam *it = (struct osd_it_iam *)di;
5979
5980         return iam_it_load(&it->oi_it, hash);
5981 }
5982
5983 static const struct dt_index_operations osd_index_iam_ops = {
5984         .dio_lookup         = osd_index_iam_lookup,
5985         .dio_declare_insert = osd_index_declare_iam_insert,
5986         .dio_insert         = osd_index_iam_insert,
5987         .dio_declare_delete = osd_index_declare_iam_delete,
5988         .dio_delete         = osd_index_iam_delete,
5989         .dio_it     = {
5990                 .init     = osd_it_iam_init,
5991                 .fini     = osd_it_iam_fini,
5992                 .get      = osd_it_iam_get,
5993                 .put      = osd_it_iam_put,
5994                 .next     = osd_it_iam_next,
5995                 .key      = osd_it_iam_key,
5996                 .key_size = osd_it_iam_key_size,
5997                 .rec      = osd_it_iam_rec,
5998                 .store    = osd_it_iam_store,
5999                 .load     = osd_it_iam_load
6000         }
6001 };
6002
6003
6004 /**
6005  * Creates or initializes iterator context.
6006  *
6007  * \retval struct osd_it_ea, iterator structure on success
6008  *
6009  */
6010 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
6011                                     struct dt_object *dt,
6012                                     __u32 attr)
6013 {
6014         struct osd_object       *obj  = osd_dt_obj(dt);
6015         struct osd_thread_info  *info = osd_oti_get(env);
6016         struct osd_it_ea        *oie;
6017         struct file             *file;
6018         struct lu_object        *lo   = &dt->do_lu;
6019         struct dentry           *obj_dentry;
6020         ENTRY;
6021
6022         if (!dt_object_exists(dt) || obj->oo_destroyed)
6023                 RETURN(ERR_PTR(-ENOENT));
6024
6025         OBD_SLAB_ALLOC_PTR_GFP(oie, osd_itea_cachep, GFP_NOFS);
6026         if (oie == NULL)
6027                 RETURN(ERR_PTR(-ENOMEM));
6028         obj_dentry = &oie->oie_dentry;
6029
6030         obj_dentry->d_inode = obj->oo_inode;
6031         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
6032         obj_dentry->d_name.hash = 0;
6033
6034         oie->oie_rd_dirent       = 0;
6035         oie->oie_it_dirent       = 0;
6036         oie->oie_dirent          = NULL;
6037         if (unlikely(!info->oti_it_ea_buf_used)) {
6038                 oie->oie_buf = info->oti_it_ea_buf;
6039                 info->oti_it_ea_buf_used = 1;
6040         } else {
6041                 OBD_ALLOC(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6042                 if (oie->oie_buf == NULL)
6043                         RETURN(ERR_PTR(-ENOMEM));
6044         }
6045         oie->oie_obj             = obj;
6046
6047         file = &oie->oie_file;
6048
6049         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
6050         if (attr & LUDA_64BITHASH)
6051                 file->f_mode    = FMODE_64BITHASH;
6052         else
6053                 file->f_mode    = FMODE_32BITHASH;
6054         file->f_path.dentry     = obj_dentry;
6055         file->f_mapping         = obj->oo_inode->i_mapping;
6056         file->f_op              = obj->oo_inode->i_fop;
6057         set_file_inode(file, obj->oo_inode);
6058
6059         lu_object_get(lo);
6060         RETURN((struct dt_it *) oie);
6061 }
6062
6063 /**
6064  * Destroy or finishes iterator context.
6065  *
6066  * \param di iterator structure to be destroyed
6067  */
6068 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
6069 {
6070         struct osd_thread_info  *info = osd_oti_get(env);
6071         struct osd_it_ea        *oie    = (struct osd_it_ea *)di;
6072         struct osd_object       *obj    = oie->oie_obj;
6073         struct inode            *inode  = obj->oo_inode;
6074
6075         ENTRY;
6076         oie->oie_file.f_op->release(inode, &oie->oie_file);
6077         osd_object_put(env, obj);
6078         if (unlikely(oie->oie_buf != info->oti_it_ea_buf))
6079                 OBD_FREE(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6080         else
6081                 info->oti_it_ea_buf_used = 0;
6082         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
6083         EXIT;
6084 }
6085
6086 /**
6087  * It position the iterator at given key, so that next lookup continues from
6088  * that key Or it is similar to dio_it->load() but based on a key,
6089  * rather than file position.
6090  *
6091  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
6092  * to the beginning.
6093  *
6094  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
6095  */
6096 static int osd_it_ea_get(const struct lu_env *env,
6097                          struct dt_it *di, const struct dt_key *key)
6098 {
6099         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
6100
6101         ENTRY;
6102         LASSERT(((const char *)key)[0] == '\0');
6103         it->oie_file.f_pos      = 0;
6104         it->oie_rd_dirent       = 0;
6105         it->oie_it_dirent       = 0;
6106         it->oie_dirent          = NULL;
6107
6108         RETURN(+1);
6109 }
6110
6111 /**
6112  * Does nothing
6113  */
6114 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
6115 {
6116 }
6117
6118 struct osd_filldir_cbs {
6119 #ifdef HAVE_DIR_CONTEXT
6120         struct dir_context ctx;
6121 #endif
6122         struct osd_it_ea  *it;
6123 };
6124 /**
6125  * It is called internally by ->readdir(). It fills the
6126  * iterator's in-memory data structure with required
6127  * information i.e. name, namelen, rec_size etc.
6128  *
6129  * \param buf in which information to be filled in.
6130  * \param name name of the file in given dir
6131  *
6132  * \retval 0 on success
6133  * \retval 1 on buffer full
6134  */
6135 #ifdef HAVE_FILLDIR_USE_CTX
6136 static int osd_ldiskfs_filldir(struct dir_context *buf,
6137 #else
6138 static int osd_ldiskfs_filldir(void *buf,
6139 #endif
6140                                const char *name, int namelen,
6141                                loff_t offset, __u64 ino, unsigned d_type)
6142 {
6143         struct osd_it_ea        *it   =
6144                 ((struct osd_filldir_cbs *)buf)->it;
6145         struct osd_object       *obj  = it->oie_obj;
6146         struct osd_it_ea_dirent *ent  = it->oie_dirent;
6147         struct lu_fid           *fid  = &ent->oied_fid;
6148         struct osd_fid_pack     *rec;
6149         ENTRY;
6150
6151         /* this should never happen */
6152         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
6153                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
6154                 RETURN(-EIO);
6155         }
6156
6157         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
6158             OSD_IT_EA_BUFSIZE)
6159                 RETURN(1);
6160
6161         /* "." is just the object itself. */
6162         if (namelen == 1 && name[0] == '.') {
6163                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
6164         } else if (d_type & LDISKFS_DIRENT_LUFID) {
6165                 rec = (struct osd_fid_pack*) (name + namelen + 1);
6166                 if (osd_fid_unpack(fid, rec) != 0)
6167                         fid_zero(fid);
6168         } else {
6169                 fid_zero(fid);
6170         }
6171         d_type &= ~LDISKFS_DIRENT_LUFID;
6172
6173         /* NOT export local root. */
6174         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
6175                 ino = obj->oo_inode->i_ino;
6176                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
6177         }
6178
6179         ent->oied_ino     = ino;
6180         ent->oied_off     = offset;
6181         ent->oied_namelen = namelen;
6182         ent->oied_type    = d_type;
6183
6184         memcpy(ent->oied_name, name, namelen);
6185
6186         it->oie_rd_dirent++;
6187         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
6188         RETURN(0);
6189 }
6190
6191 /**
6192  * Calls ->readdir() to load a directory entry at a time
6193  * and stored it in iterator's in-memory data structure.
6194  *
6195  * \param di iterator's in memory structure
6196  *
6197  * \retval   0 on success
6198  * \retval -ve on error
6199  * \retval +1 reach the end of entry
6200  */
6201 static int osd_ldiskfs_it_fill(const struct lu_env *env,
6202                                const struct dt_it *di)
6203 {
6204         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
6205         struct osd_object  *obj   = it->oie_obj;
6206         struct inode       *inode = obj->oo_inode;
6207         struct htree_lock  *hlock = NULL;
6208         struct file        *filp  = &it->oie_file;
6209         int                 rc = 0;
6210         struct osd_filldir_cbs buf = {
6211 #ifdef HAVE_DIR_CONTEXT
6212                 .ctx.actor = osd_ldiskfs_filldir,
6213 #endif
6214                 .it = it
6215         };
6216
6217         ENTRY;
6218         it->oie_dirent = it->oie_buf;
6219         it->oie_rd_dirent = 0;
6220
6221         if (obj->oo_hl_head != NULL) {
6222                 hlock = osd_oti_get(env)->oti_hlock;
6223                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
6224                                    inode, LDISKFS_HLOCK_READDIR);
6225         } else {
6226                 down_read(&obj->oo_ext_idx_sem);
6227         }
6228
6229 #ifdef HAVE_DIR_CONTEXT
6230         buf.ctx.pos = filp->f_pos;
6231         rc = inode->i_fop->iterate(filp, &buf.ctx);
6232         filp->f_pos = buf.ctx.pos;
6233 #else
6234         rc = inode->i_fop->readdir(filp, &buf, osd_ldiskfs_filldir);
6235 #endif
6236
6237         if (hlock != NULL)
6238                 ldiskfs_htree_unlock(hlock);
6239         else
6240                 up_read(&obj->oo_ext_idx_sem);
6241
6242         if (it->oie_rd_dirent == 0) {
6243                 /*If it does not get any dirent, it means it has been reached
6244                  *to the end of the dir */
6245                 it->oie_file.f_pos = ldiskfs_get_htree_eof(&it->oie_file);
6246                 if (rc == 0)
6247                         rc = 1;
6248         } else {
6249                 it->oie_dirent = it->oie_buf;
6250                 it->oie_it_dirent = 1;
6251         }
6252
6253         RETURN(rc);
6254 }
6255
6256 /**
6257  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
6258  * to load a directory entry at a time and stored it in
6259  * iterator's in-memory data structure.
6260  *
6261  * \param di iterator's in memory structure
6262  *
6263  * \retval +ve iterator reached to end
6264  * \retval   0 iterator not reached to end
6265  * \retval -ve on error
6266  */
6267 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
6268 {
6269         struct osd_it_ea *it = (struct osd_it_ea *)di;
6270         int rc;
6271
6272         ENTRY;
6273
6274         if (it->oie_it_dirent < it->oie_rd_dirent) {
6275                 it->oie_dirent =
6276                         (void *) it->oie_dirent +
6277                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
6278                                        it->oie_dirent->oied_namelen);
6279                 it->oie_it_dirent++;
6280                 RETURN(0);
6281         } else {
6282                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
6283                         rc = +1;
6284                 else
6285                         rc = osd_ldiskfs_it_fill(env, di);
6286         }
6287
6288         RETURN(rc);
6289 }
6290
6291 /**
6292  * Returns the key at current position from iterator's in memory structure.
6293  *
6294  * \param di iterator's in memory structure
6295  *
6296  * \retval key i.e. struct dt_key on success
6297  */
6298 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
6299                                     const struct dt_it *di)
6300 {
6301         struct osd_it_ea *it = (struct osd_it_ea *)di;
6302
6303         return (struct dt_key *)it->oie_dirent->oied_name;
6304 }
6305
6306 /**
6307  * Returns the key's size at current position from iterator's in memory structure.
6308  *
6309  * \param di iterator's in memory structure
6310  *
6311  * \retval key_size i.e. struct dt_key on success
6312  */
6313 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
6314 {
6315         struct osd_it_ea *it = (struct osd_it_ea *)di;
6316
6317         return it->oie_dirent->oied_namelen;
6318 }
6319
6320 static inline bool osd_dotdot_has_space(struct ldiskfs_dir_entry_2 *de)
6321 {
6322         if (LDISKFS_DIR_REC_LEN(de) >=
6323             __LDISKFS_DIR_REC_LEN(2 + 1 + sizeof(struct osd_fid_pack)))
6324                 return true;
6325
6326         return false;
6327 }
6328
6329 static inline bool
6330 osd_dirent_has_space(struct ldiskfs_dir_entry_2 *de, __u16 namelen,
6331                      unsigned blocksize, bool dotdot)
6332 {
6333         if (dotdot)
6334                 return osd_dotdot_has_space(de);
6335
6336         if (ldiskfs_rec_len_from_disk(de->rec_len, blocksize) >=
6337             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
6338                 return true;
6339
6340         return false;
6341 }
6342
6343 static int
6344 osd_dirent_reinsert(const struct lu_env *env, struct osd_device *dev,
6345                     handle_t *jh, struct dentry *dentry,
6346                     const struct lu_fid *fid, struct buffer_head *bh,
6347                     struct ldiskfs_dir_entry_2 *de, struct htree_lock *hlock,
6348                     bool dotdot)
6349 {
6350         struct inode                *dir        = dentry->d_parent->d_inode;
6351         struct inode                *inode      = dentry->d_inode;
6352         struct osd_fid_pack         *rec;
6353         struct ldiskfs_dentry_param *ldp;
6354         int                          namelen    = dentry->d_name.len;
6355         int                          rc;
6356         struct osd_thread_info     *info        = osd_oti_get(env);
6357         ENTRY;
6358
6359         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
6360                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
6361                 RETURN(0);
6362
6363         /* There is enough space to hold the FID-in-dirent. */
6364         if (osd_dirent_has_space(de, namelen, dir->i_sb->s_blocksize, dotdot)) {
6365                 rc = ldiskfs_journal_get_write_access(jh, bh);
6366                 if (rc != 0)
6367                         RETURN(rc);
6368
6369                 de->name[namelen] = 0;
6370                 rec = (struct osd_fid_pack *)(de->name + namelen + 1);
6371                 rec->fp_len = sizeof(struct lu_fid) + 1;
6372                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
6373                 de->file_type |= LDISKFS_DIRENT_LUFID;
6374                 rc = ldiskfs_handle_dirty_metadata(jh, NULL, bh);
6375
6376                 RETURN(rc);
6377         }
6378
6379         LASSERT(!dotdot);
6380
6381         rc = ldiskfs_delete_entry(jh, dir, de, bh);
6382         if (rc != 0)
6383                 RETURN(rc);
6384
6385         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
6386         osd_get_ldiskfs_dirent_param(ldp, fid);
6387         dentry->d_fsdata = (void *)ldp;
6388         ll_vfs_dq_init(dir);
6389         rc = osd_ldiskfs_add_entry(info, dev, jh, dentry, inode, hlock);
6390         /* It is too bad, we cannot reinsert the name entry back.
6391          * That means we lose it! */
6392         if (rc != 0)
6393                 CDEBUG(D_LFSCK, "%s: fail to reinsert the dirent, "
6394                        "dir = %lu/%u, name = %.*s, "DFID": rc = %d\n",
6395                        osd_ino2name(inode),
6396                        dir->i_ino, dir->i_generation, namelen,
6397                        dentry->d_name.name, PFID(fid), rc);
6398
6399         RETURN(rc);
6400 }
6401
6402 static int
6403 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
6404                         struct osd_it_ea *it, struct lu_fid *fid,
6405                         struct osd_inode_id *id, __u32 *attr)
6406 {
6407         struct osd_thread_info     *info        = osd_oti_get(env);
6408         struct lustre_mdt_attrs    *lma         = &info->oti_ost_attrs.loa_lma;
6409         struct osd_device          *dev         = osd_obj2dev(obj);
6410         struct super_block         *sb          = osd_sb(dev);
6411         const char                 *devname     = osd_name(dev);
6412         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
6413         struct inode               *dir         = obj->oo_inode;
6414         struct htree_lock          *hlock       = NULL;
6415         struct buffer_head         *bh          = NULL;
6416         handle_t                   *jh          = NULL;
6417         struct ldiskfs_dir_entry_2 *de;
6418         struct dentry              *dentry;
6419         struct inode               *inode;
6420         const struct lu_fid *pfid = lu_object_fid(&obj->oo_dt.do_lu);
6421         int                         credits;
6422         int                         rc;
6423         bool                        dotdot      = false;
6424         bool                        dirty       = false;
6425         ENTRY;
6426
6427         if (ent->oied_name[0] == '.') {
6428                 if (ent->oied_namelen == 1)
6429                         RETURN(0);
6430
6431                 if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
6432                         dotdot = true;
6433         }
6434
6435         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
6436         inode = osd_iget(info, dev, id);
6437         if (IS_ERR(inode)) {
6438                 rc = PTR_ERR(inode);
6439                 if (rc == -ENOENT || rc == -ESTALE) {
6440                         /* Maybe dangling name entry, or
6441                          * corrupted directory entry. */
6442                         *attr |= LUDA_UNKNOWN;
6443                         rc = 0;
6444                 } else {
6445                         CDEBUG(D_LFSCK, "%s: fail to iget() for dirent "
6446                                "check_repair, dir = %lu/%u, name = %.*s, "
6447                                "ino = %llu, rc = %d\n",
6448                                devname, dir->i_ino, dir->i_generation,
6449                                ent->oied_namelen, ent->oied_name,
6450                                ent->oied_ino, rc);
6451                 }
6452
6453                 RETURN(rc);
6454         }
6455
6456         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
6457                                            ent->oied_namelen);
6458         rc = osd_get_lma(info, inode, dentry, &info->oti_ost_attrs);
6459         if (rc == -ENODATA || !fid_is_sane(&lma->lma_self_fid))
6460                 lma = NULL;
6461         else if (rc != 0)
6462                 GOTO(out, rc);
6463
6464         /* We need to ensure that the name entry is still valid.
6465          * Because it may be removed or renamed by other already.
6466          *
6467          * The unlink or rename operation will start journal before PDO lock,
6468          * so to avoid deadlock, here we need to start journal handle before
6469          * related PDO lock also. But because we do not know whether there
6470          * will be something to be repaired before PDO lock, we just start
6471          * journal without conditions.
6472          *
6473          * We may need to remove the name entry firstly, then insert back.
6474          * One credit is for user quota file update.
6475          * One credit is for group quota file update.
6476          * Two credits are for dirty inode. */
6477         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
6478                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
6479
6480         if (dev->od_dirent_journal != 0) {
6481
6482 again:
6483                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
6484                 if (IS_ERR(jh)) {
6485                         rc = PTR_ERR(jh);
6486                         CDEBUG(D_LFSCK, "%s: fail to start trans for dirent "
6487                                "check_repair, dir = %lu/%u, credits = %d, "
6488                                "name = %.*s, ino = %llu: rc = %d\n",
6489                                devname, dir->i_ino, dir->i_generation, credits,
6490                                ent->oied_namelen, ent->oied_name,
6491                                ent->oied_ino, rc);
6492
6493                         GOTO(out_inode, rc);
6494                 }
6495
6496                 if (obj->oo_hl_head != NULL) {
6497                         hlock = osd_oti_get(env)->oti_hlock;
6498                         /* "0" means exclusive lock for the whole directory.
6499                          * We need to prevent others access such name entry
6500                          * during the delete + insert. Neither HLOCK_ADD nor
6501                          * HLOCK_DEL cannot guarantee the atomicity. */
6502                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
6503                 } else {
6504                         down_write(&obj->oo_ext_idx_sem);
6505                 }
6506         } else {
6507                 if (obj->oo_hl_head != NULL) {
6508                         hlock = osd_oti_get(env)->oti_hlock;
6509                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
6510                                            LDISKFS_HLOCK_LOOKUP);
6511                 } else {
6512                         down_read(&obj->oo_ext_idx_sem);
6513                 }
6514         }
6515
6516         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
6517         if (IS_ERR(bh) || le32_to_cpu(de->inode) != inode->i_ino) {
6518                 *attr |= LUDA_IGNORE;
6519
6520                 GOTO(out, rc = 0);
6521         }
6522
6523         /* For dotdot entry, if there is not enough space to hold the
6524          * FID-in-dirent, just keep them there. It only happens when the
6525          * device upgraded from 1.8 or restored from MDT file-level backup.
6526          * For the whole directory, only dotdot entry have no FID-in-dirent
6527          * and needs to get FID from LMA when readdir, it will not affect the
6528          * performance much. */
6529         if (dotdot && !osd_dotdot_has_space(de)) {
6530                 *attr |= LUDA_UNKNOWN;
6531
6532                 GOTO(out, rc = 0);
6533         }
6534
6535         if (lma != NULL) {
6536                 if (lu_fid_eq(fid, &lma->lma_self_fid))
6537                         GOTO(out, rc = 0);
6538
6539                 if (unlikely(lma->lma_compat & LMAC_NOT_IN_OI)) {
6540                         struct lu_fid *tfid = &lma->lma_self_fid;
6541
6542                         if (likely(dotdot &&
6543                                    fid_seq(tfid) == FID_SEQ_LOCAL_FILE &&
6544                                    fid_oid(tfid) == REMOTE_PARENT_DIR_OID)) {
6545                                 /* It must be REMOTE_PARENT_DIR and as the
6546                                  * 'dotdot' entry of remote directory */
6547                                 *attr |= LUDA_IGNORE;
6548                         } else {
6549                                 CDEBUG(D_LFSCK, "%s: expect remote agent "
6550                                        "parent directory, but got %.*s under "
6551                                        "dir = %lu/%u with the FID "DFID"\n",
6552                                        devname, ent->oied_namelen,
6553                                        ent->oied_name, dir->i_ino,
6554                                        dir->i_generation, PFID(tfid));
6555
6556                                 *attr |= LUDA_UNKNOWN;
6557                         }
6558
6559                         GOTO(out, rc = 0);
6560                 }
6561         }
6562
6563         if (!fid_is_zero(fid)) {
6564                 rc = osd_verify_ent_by_linkea(env, inode, pfid, ent->oied_name,
6565                                               ent->oied_namelen);
6566                 if (rc == -ENOENT ||
6567                     (rc == -ENODATA &&
6568                      !(dev->od_scrub.os_scrub.os_file.sf_flags & SF_UPGRADE))) {
6569                         /* linkEA does not recognize the dirent entry,
6570                          * it may because the dirent entry corruption
6571                          * and points to other's inode. */
6572                         CDEBUG(D_LFSCK, "%s: the target inode does not "
6573                                "recognize the dirent, dir = %lu/%u, "
6574                                " name = %.*s, ino = %llu, "
6575                                DFID": rc = %d\n", devname, dir->i_ino,
6576                                dir->i_generation, ent->oied_namelen,
6577                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
6578                         *attr |= LUDA_UNKNOWN;
6579
6580                         GOTO(out, rc = 0);
6581                 }
6582
6583                 if (rc && rc != -ENODATA) {
6584                         CDEBUG(D_LFSCK, "%s: fail to verify FID in the dirent, "
6585                                "dir = %lu/%u, name = %.*s, ino = %llu, "
6586                                DFID": rc = %d\n", devname, dir->i_ino,
6587                                dir->i_generation, ent->oied_namelen,
6588                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
6589                         *attr |= LUDA_UNKNOWN;
6590
6591                         GOTO(out, rc = 0);
6592                 }
6593         }
6594
6595         if (lma != NULL) {
6596                 /* linkEA recognizes the dirent entry, the FID-in-LMA is
6597                  * valid, trusted, in spite of fid_is_sane(fid) or not. */
6598                 if (*attr & LUDA_VERIFY_DRYRUN) {
6599                         *fid = lma->lma_self_fid;
6600                         *attr |= LUDA_REPAIR;
6601
6602                         GOTO(out, rc = 0);
6603                 }
6604
6605                 if (jh == NULL) {
6606                         brelse(bh);
6607                         dev->od_dirent_journal = 1;
6608                         if (hlock != NULL) {
6609                                 ldiskfs_htree_unlock(hlock);
6610                                 hlock = NULL;
6611                         } else {
6612                                 up_read(&obj->oo_ext_idx_sem);
6613                         }
6614
6615                         goto again;
6616                 }
6617
6618                 *fid = lma->lma_self_fid;
6619                 dirty = true;
6620                 /* Update or append the FID-in-dirent. */
6621                 rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
6622                                          bh, de, hlock, dotdot);
6623                 if (rc == 0)
6624                         *attr |= LUDA_REPAIR;
6625                 else
6626                         CDEBUG(D_LFSCK, "%s: fail to re-insert FID after "
6627                                "the dirent, dir = %lu/%u, name = %.*s, "
6628                                "ino = %llu, "DFID": rc = %d\n",
6629                                devname, dir->i_ino, dir->i_generation,
6630                                ent->oied_namelen, ent->oied_name,
6631                                ent->oied_ino, PFID(fid), rc);
6632         } else {
6633                 /* lma is NULL, trust the FID-in-dirent if it is valid. */
6634                 if (*attr & LUDA_VERIFY_DRYRUN) {
6635                         if (fid_is_sane(fid)) {
6636                                 *attr |= LUDA_REPAIR;
6637                         } else if (dev->od_index == 0) {
6638                                 lu_igif_build(fid, inode->i_ino,
6639                                               inode->i_generation);
6640                                 *attr |= LUDA_UPGRADE;
6641                         }
6642
6643                         GOTO(out, rc = 0);
6644                 }
6645
6646                 if (jh == NULL) {
6647                         brelse(bh);
6648                         dev->od_dirent_journal = 1;
6649                         if (hlock != NULL) {
6650                                 ldiskfs_htree_unlock(hlock);
6651                                 hlock = NULL;
6652                         } else {
6653                                 up_read(&obj->oo_ext_idx_sem);
6654                         }
6655
6656                         goto again;
6657                 }
6658
6659                 dirty = true;
6660                 if (unlikely(fid_is_sane(fid))) {
6661                         /* FID-in-dirent exists, but FID-in-LMA is lost.
6662                          * Trust the FID-in-dirent, and add FID-in-LMA. */
6663                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
6664                         if (rc == 0)
6665                                 *attr |= LUDA_REPAIR;
6666                         else
6667                                 CDEBUG(D_LFSCK, "%s: fail to set LMA for "
6668                                        "update dirent, dir = %lu/%u, "
6669                                        "name = %.*s, ino = %llu, "
6670                                        DFID": rc = %d\n",
6671                                        devname, dir->i_ino, dir->i_generation,
6672                                        ent->oied_namelen, ent->oied_name,
6673                                        ent->oied_ino, PFID(fid), rc);
6674                 } else if (dev->od_index == 0) {
6675                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
6676                         /* It is probably IGIF object. Only aappend the
6677                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
6678                         rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
6679                                                  bh, de, hlock, dotdot);
6680                         if (rc == 0)
6681                                 *attr |= LUDA_UPGRADE;
6682                         else
6683                                 CDEBUG(D_LFSCK, "%s: fail to append IGIF "
6684                                        "after the dirent, dir = %lu/%u, "
6685                                        "name = %.*s, ino = %llu, "
6686                                        DFID": rc = %d\n",
6687                                        devname, dir->i_ino, dir->i_generation,
6688                                        ent->oied_namelen, ent->oied_name,
6689                                        ent->oied_ino, PFID(fid), rc);
6690                 }
6691         }
6692
6693         GOTO(out, rc);
6694
6695 out:
6696         if (!IS_ERR(bh))
6697                 brelse(bh);
6698         if (hlock != NULL) {
6699                 ldiskfs_htree_unlock(hlock);
6700         } else {
6701                 if (dev->od_dirent_journal != 0)
6702                         up_write(&obj->oo_ext_idx_sem);
6703                 else
6704                         up_read(&obj->oo_ext_idx_sem);
6705         }
6706
6707         if (jh != NULL)
6708                 ldiskfs_journal_stop(jh);
6709
6710 out_inode:
6711         iput(inode);
6712         if (rc >= 0 && !dirty)
6713                 dev->od_dirent_journal = 0;
6714
6715         return rc;
6716 }
6717
6718 /**
6719  * Returns the value at current position from iterator's in memory structure.
6720  *
6721  * \param di struct osd_it_ea, iterator's in memory structure
6722  * \param attr attr requested for dirent.
6723  * \param lde lustre dirent
6724  *
6725  * \retval   0 no error and \param lde has correct lustre dirent.
6726  * \retval -ve on error
6727  */
6728 static inline int osd_it_ea_rec(const struct lu_env *env,
6729                                 const struct dt_it *di,
6730                                 struct dt_rec *dtrec, __u32 attr)
6731 {
6732         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
6733         struct osd_object      *obj   = it->oie_obj;
6734         struct osd_device      *dev   = osd_obj2dev(obj);
6735         struct osd_thread_info *oti   = osd_oti_get(env);
6736         struct osd_inode_id    *id    = &oti->oti_id;
6737         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
6738         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
6739         __u32                   ino   = it->oie_dirent->oied_ino;
6740         int                     rc    = 0;
6741         ENTRY;
6742
6743         LASSERT(obj->oo_inode != dev->od_mdt_map->omm_remote_parent->d_inode);
6744
6745         if (attr & LUDA_VERIFY) {
6746                 if (unlikely(ino == osd_remote_parent_ino(dev))) {
6747                         attr |= LUDA_IGNORE;
6748                         /* If the parent is on remote MDT, and there
6749                          * is no FID-in-dirent, then we have to get
6750                          * the parent FID from the linkEA.  */
6751                         if (!fid_is_sane(fid) &&
6752                             it->oie_dirent->oied_namelen == 2 &&
6753                             it->oie_dirent->oied_name[0] == '.' &&
6754                             it->oie_dirent->oied_name[1] == '.')
6755                                 osd_get_pfid_from_linkea(env, obj, fid);
6756                 } else {
6757                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
6758                                                      &attr);
6759                 }
6760
6761                 if (!fid_is_sane(fid))
6762                         attr |= LUDA_UNKNOWN;
6763         } else {
6764                 attr &= ~LU_DIRENT_ATTRS_MASK;
6765                 if (!fid_is_sane(fid)) {
6766                         bool is_dotdot = false;
6767                         if (it->oie_dirent->oied_namelen == 2 &&
6768                             it->oie_dirent->oied_name[0] == '.' &&
6769                             it->oie_dirent->oied_name[1] == '.')
6770                                 is_dotdot = true;
6771                         /* If the parent is on remote MDT, and there
6772                          * is no FID-in-dirent, then we have to get
6773                          * the parent FID from the linkEA.  */
6774                         if (ino == osd_remote_parent_ino(dev) && is_dotdot) {
6775                                 rc = osd_get_pfid_from_linkea(env, obj, fid);
6776                         } else {
6777                                 if (is_dotdot == false &&
6778                                     OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
6779                                         RETURN(-ENOENT);
6780
6781                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
6782                         }
6783                 } else {
6784                         osd_id_gen(id, ino, OSD_OII_NOGEN);
6785                 }
6786         }
6787
6788         /* Pack the entry anyway, at least the offset is right. */
6789         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
6790                            it->oie_dirent->oied_name,
6791                            it->oie_dirent->oied_namelen,
6792                            it->oie_dirent->oied_type, attr);
6793
6794         if (rc < 0)
6795                 RETURN(rc);
6796
6797         if (osd_remote_fid(env, dev, fid))
6798                 RETURN(0);
6799
6800         if (likely(!(attr & (LUDA_IGNORE | LUDA_UNKNOWN)) && rc == 0))
6801                 osd_add_oi_cache(oti, dev, id, fid);
6802
6803         RETURN(rc > 0 ? 0 : rc);
6804 }
6805
6806 /**
6807  * Returns the record size size at current position.
6808  *
6809  * This function will return record(lu_dirent) size in bytes.
6810  *
6811  * \param[in] env       execution environment
6812  * \param[in] di        iterator's in memory structure
6813  * \param[in] attr      attribute of the entry, only requires LUDA_TYPE to
6814  *                      calculate the lu_dirent size.
6815  *
6816  * \retval      record size(in bytes & in memory) of the current lu_dirent
6817  *              entry.
6818  */
6819 static int osd_it_ea_rec_size(const struct lu_env *env, const struct dt_it *di,
6820                               __u32 attr)
6821 {
6822         struct osd_it_ea *it = (struct osd_it_ea *)di;
6823
6824         return lu_dirent_calc_size(it->oie_dirent->oied_namelen, attr);
6825 }
6826
6827 /**
6828  * Returns a cookie for current position of the iterator head, so that
6829  * user can use this cookie to load/start the iterator next time.
6830  *
6831  * \param di iterator's in memory structure
6832  *
6833  * \retval cookie for current position, on success
6834  */
6835 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
6836 {
6837         struct osd_it_ea *it = (struct osd_it_ea *)di;
6838
6839         return it->oie_dirent->oied_off;
6840 }
6841
6842 /**
6843  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
6844  * to load a directory entry at a time and stored it i inn,
6845  * in iterator's in-memory data structure.
6846  *
6847  * \param di struct osd_it_ea, iterator's in memory structure
6848  *
6849  * \retval +ve on success
6850  * \retval -ve on error
6851  */
6852 static int osd_it_ea_load(const struct lu_env *env,
6853                           const struct dt_it *di, __u64 hash)
6854 {
6855         struct osd_it_ea *it = (struct osd_it_ea *)di;
6856         int rc;
6857
6858         ENTRY;
6859         it->oie_file.f_pos = hash;
6860
6861         rc =  osd_ldiskfs_it_fill(env, di);
6862         if (rc > 0)
6863                 rc = -ENODATA;
6864
6865         if (rc == 0)
6866                 rc = +1;
6867
6868         RETURN(rc);
6869 }
6870
6871 /**
6872  * Index lookup function for interoperability mode (b11826).
6873  *
6874  * \param key,  key i.e. file name to be searched
6875  *
6876  * \retval +ve, on success
6877  * \retval -ve, on error
6878  */
6879 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
6880                                struct dt_rec *rec, const struct dt_key *key)
6881 {
6882         struct osd_object *obj = osd_dt_obj(dt);
6883         int rc = 0;
6884
6885         ENTRY;
6886
6887         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
6888         LINVRNT(osd_invariant(obj));
6889
6890         rc = osd_ea_lookup_rec(env, obj, rec, key);
6891         if (rc == 0)
6892                 rc = +1;
6893         RETURN(rc);
6894 }
6895
6896 /**
6897  * Index and Iterator operations for interoperability
6898  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
6899  */
6900 static const struct dt_index_operations osd_index_ea_ops = {
6901         .dio_lookup         = osd_index_ea_lookup,
6902         .dio_declare_insert = osd_index_declare_ea_insert,
6903         .dio_insert         = osd_index_ea_insert,
6904         .dio_declare_delete = osd_index_declare_ea_delete,
6905         .dio_delete         = osd_index_ea_delete,
6906         .dio_it     = {
6907                 .init     = osd_it_ea_init,
6908                 .fini     = osd_it_ea_fini,
6909                 .get      = osd_it_ea_get,
6910                 .put      = osd_it_ea_put,
6911                 .next     = osd_it_ea_next,
6912                 .key      = osd_it_ea_key,
6913                 .key_size = osd_it_ea_key_size,
6914                 .rec      = osd_it_ea_rec,
6915                 .rec_size = osd_it_ea_rec_size,
6916                 .store    = osd_it_ea_store,
6917                 .load     = osd_it_ea_load
6918         }
6919 };
6920
6921 static void *osd_key_init(const struct lu_context *ctx,
6922                           struct lu_context_key *key)
6923 {
6924         struct osd_thread_info *info;
6925
6926         OBD_ALLOC_PTR(info);
6927         if (info == NULL)
6928                 return ERR_PTR(-ENOMEM);
6929
6930         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
6931         if (info->oti_it_ea_buf == NULL)
6932                 goto out_free_info;
6933
6934         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
6935
6936         info->oti_hlock = ldiskfs_htree_lock_alloc();
6937         if (info->oti_hlock == NULL)
6938                 goto out_free_ea;
6939
6940         return info;
6941
6942  out_free_ea:
6943         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
6944  out_free_info:
6945         OBD_FREE_PTR(info);
6946         return ERR_PTR(-ENOMEM);
6947 }
6948
6949 static void osd_key_fini(const struct lu_context *ctx,
6950                          struct lu_context_key *key, void* data)
6951 {
6952         struct osd_thread_info *info = data;
6953         struct ldiskfs_inode_info *lli = LDISKFS_I(info->oti_inode);
6954         struct osd_idmap_cache  *idc = info->oti_ins_cache;
6955
6956         if (info->oti_inode != NULL)
6957                 OBD_FREE_PTR(lli);
6958         if (info->oti_hlock != NULL)
6959                 ldiskfs_htree_lock_free(info->oti_hlock);
6960         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
6961         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
6962         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
6963         lu_buf_free(&info->oti_big_buf);
6964         if (idc != NULL) {
6965                 LASSERT(info->oti_ins_cache_size > 0);
6966                 OBD_FREE(idc, sizeof(*idc) * info->oti_ins_cache_size);
6967                 info->oti_ins_cache = NULL;
6968                 info->oti_ins_cache_size = 0;
6969         }
6970         OBD_FREE_PTR(info);
6971 }
6972
6973 static void osd_key_exit(const struct lu_context *ctx,
6974                          struct lu_context_key *key, void *data)
6975 {
6976         struct osd_thread_info *info = data;
6977
6978         LASSERT(info->oti_r_locks == 0);
6979         LASSERT(info->oti_w_locks == 0);
6980         LASSERT(info->oti_txns    == 0);
6981 }
6982
6983 /* type constructor/destructor: osd_type_init, osd_type_fini */
6984 LU_TYPE_INIT_FINI(osd, &osd_key);
6985
6986 struct lu_context_key osd_key = {
6987         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
6988         .lct_init = osd_key_init,
6989         .lct_fini = osd_key_fini,
6990         .lct_exit = osd_key_exit
6991 };
6992
6993
6994 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
6995                            const char *name, struct lu_device *next)
6996 {
6997         struct osd_device *osd = osd_dev(d);
6998
6999         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
7000             >= sizeof(osd->od_svname))
7001                 return -E2BIG;
7002         return osd_procfs_init(osd, name);
7003 }
7004
7005 static int osd_fid_init(const struct lu_env *env, struct osd_device *osd)
7006 {
7007         struct seq_server_site  *ss = osd_seq_site(osd);
7008         int                     rc;
7009         ENTRY;
7010
7011         if (osd->od_is_ost || osd->od_cl_seq != NULL)
7012                 RETURN(0);
7013
7014         if (unlikely(ss == NULL))
7015                 RETURN(-ENODEV);
7016
7017         OBD_ALLOC_PTR(osd->od_cl_seq);
7018         if (osd->od_cl_seq == NULL)
7019                 RETURN(-ENOMEM);
7020
7021         rc = seq_client_init(osd->od_cl_seq, NULL, LUSTRE_SEQ_METADATA,
7022                              osd->od_svname, ss->ss_server_seq);
7023         if (rc != 0) {
7024                 OBD_FREE_PTR(osd->od_cl_seq);
7025                 osd->od_cl_seq = NULL;
7026                 RETURN(rc);
7027         }
7028
7029         if (ss->ss_node_id == 0) {
7030                 /* If the OSD on the sequence controller(MDT0), then allocate
7031                  * sequence here, otherwise allocate sequence after connected
7032                  * to MDT0 (see mdt_register_lwp_callback()). */
7033                 rc = seq_server_alloc_meta(osd->od_cl_seq->lcs_srv,
7034                                    &osd->od_cl_seq->lcs_space, env);
7035         }
7036
7037         RETURN(rc);
7038 }
7039
7040 static void osd_fid_fini(const struct lu_env *env, struct osd_device *osd)
7041 {
7042         if (osd->od_cl_seq == NULL)
7043                 return;
7044
7045         seq_client_fini(osd->od_cl_seq);
7046         OBD_FREE_PTR(osd->od_cl_seq);
7047         osd->od_cl_seq = NULL;
7048 }
7049
7050 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
7051 {
7052         ENTRY;
7053
7054         /* shutdown quota slave instance associated with the device */
7055         if (o->od_quota_slave != NULL) {
7056                 struct qsd_instance *qsd = o->od_quota_slave;
7057
7058                 o->od_quota_slave = NULL;
7059                 qsd_fini(env, qsd);
7060         }
7061
7062         osd_fid_fini(env, o);
7063         osd_scrub_cleanup(env, o);
7064
7065         RETURN(0);
7066 }
7067
7068 static void osd_umount(const struct lu_env *env, struct osd_device *o)
7069 {
7070         ENTRY;
7071
7072         if (o->od_mnt != NULL) {
7073                 shrink_dcache_sb(osd_sb(o));
7074                 osd_sync(env, &o->od_dt_dev);
7075
7076                 mntput(o->od_mnt);
7077                 o->od_mnt = NULL;
7078         }
7079
7080         EXIT;
7081 }
7082
7083 static int osd_mount(const struct lu_env *env,
7084                      struct osd_device *o, struct lustre_cfg *cfg)
7085 {
7086         const char              *name  = lustre_cfg_string(cfg, 0);
7087         const char              *dev  = lustre_cfg_string(cfg, 1);
7088         const char              *opts;
7089         unsigned long            page, s_flags, lmd_flags = 0;
7090         struct page             *__page;
7091         struct file_system_type *type;
7092         char                    *options = NULL;
7093         char                    *str;
7094         struct osd_thread_info  *info = osd_oti_get(env);
7095         struct lu_fid           *fid = &info->oti_fid;
7096         struct inode            *inode;
7097         int                      rc = 0, force_over_512tb = 0;
7098         ENTRY;
7099
7100         if (o->od_mnt != NULL)
7101                 RETURN(0);
7102
7103         if (strlen(dev) >= sizeof(o->od_mntdev))
7104                 RETURN(-E2BIG);
7105         strcpy(o->od_mntdev, dev);
7106
7107         str = lustre_cfg_string(cfg, 2);
7108         s_flags = simple_strtoul(str, NULL, 0);
7109         str = strstr(str, ":");
7110         if (str)
7111                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
7112         opts = lustre_cfg_string(cfg, 3);
7113 #ifdef __BIG_ENDIAN
7114         if (opts == NULL || strstr(opts, "bigendian_extents") == NULL) {
7115                 CERROR("%s: device %s extents feature is not guaranteed to "
7116                        "work on big-endian systems. Use \"bigendian_extents\" "
7117                        "mount option to override.\n", name, dev);
7118                 RETURN(-EINVAL);
7119         }
7120 #endif
7121 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7122         if (opts != NULL && strstr(opts, "force_over_128tb") != NULL) {
7123                 CWARN("force_over_128tb option is deprecated. "
7124                       "Filesystems less than 512TB can be created without any "
7125                       "force options. Use force_over_512tb option for "
7126                       "filesystems greater than 512TB.\n");
7127         }
7128 #endif
7129 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 1, 53, 0)
7130         if (opts != NULL && strstr(opts, "force_over_256tb") != NULL) {
7131                 CWARN("force_over_256tb 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
7138         if (opts != NULL && strstr(opts, "force_over_512tb") != NULL)
7139                 force_over_512tb = 1;
7140
7141         __page = alloc_page(GFP_KERNEL);
7142         if (__page == NULL)
7143                 GOTO(out, rc = -ENOMEM);
7144         page = (unsigned long)page_address(__page);
7145         options = (char *)page;
7146         *options = '\0';
7147         if (opts != NULL) {
7148                 /* strip out the options for back compatiblity */
7149                 static char *sout[] = {
7150                         "mballoc",
7151                         "iopen",
7152                         "noiopen",
7153                         "iopen_nopriv",
7154                         "extents",
7155                         "noextents",
7156                         /* strip out option we processed in osd */
7157                         "bigendian_extents",
7158                         "force_over_128tb",
7159                         "force_over_256tb",
7160                         "force_over_512tb",
7161                         NULL
7162                 };
7163                 strcat(options, opts);
7164                 for (rc = 0, str = options; sout[rc]; ) {
7165                         char *op = strstr(str, sout[rc]);
7166                         if (op == NULL) {
7167                                 rc++;
7168                                 str = options;
7169                                 continue;
7170                         }
7171                         if (op == options || *(op - 1) == ',') {
7172                                 str = op + strlen(sout[rc]);
7173                                 if (*str == ',' || *str == '\0') {
7174                                         *str == ',' ? str++ : str;
7175                                         memmove(op, str, strlen(str) + 1);
7176                                 }
7177                         }
7178                         for (str = op; *str != ',' && *str != '\0'; str++)
7179                                 ;
7180                 }
7181         } else {
7182                 strncat(options, "user_xattr,acl", 14);
7183         }
7184
7185         /* Glom up mount options */
7186         if (*options != '\0')
7187                 strcat(options, ",");
7188         strlcat(options, "no_mbcache,nodelalloc", PAGE_SIZE);
7189
7190         type = get_fs_type("ldiskfs");
7191         if (!type) {
7192                 CERROR("%s: cannot find ldiskfs module\n", name);
7193                 GOTO(out, rc = -ENODEV);
7194         }
7195
7196         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
7197         module_put(type->owner);
7198
7199         if (IS_ERR(o->od_mnt)) {
7200                 rc = PTR_ERR(o->od_mnt);
7201                 o->od_mnt = NULL;
7202                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
7203                 GOTO(out, rc);
7204         }
7205
7206         if (ldiskfs_blocks_count(LDISKFS_SB(osd_sb(o))->s_es) <<
7207                                  osd_sb(o)->s_blocksize_bits > 512ULL << 40 &&
7208                                  force_over_512tb == 0) {
7209                 CERROR("%s: device %s LDISKFS does not support filesystems "
7210                        "greater than 512TB and can cause data corruption. "
7211                        "Use \"force_over_512tb\" mount option to override.\n",
7212                        name, dev);
7213                 GOTO(out_mnt, rc = -EINVAL);
7214         }
7215
7216         if (lmd_flags & LMD_FLG_DEV_RDONLY) {
7217                 if (priv_dev_set_rdonly) {
7218                         priv_dev_set_rdonly(osd_sb(o)->s_bdev);
7219                         o->od_dt_dev.dd_rdonly = 1;
7220                         LCONSOLE_WARN("%s: set dev_rdonly on this device\n",
7221                                       name);
7222                 } else {
7223                         LCONSOLE_WARN("%s: not support dev_rdonly on this device",
7224                                       name);
7225
7226                         GOTO(out_mnt, rc = -EOPNOTSUPP);
7227                 }
7228         } else if (priv_dev_check_rdonly &&
7229                    priv_dev_check_rdonly(osd_sb(o)->s_bdev)) {
7230                 CERROR("%s: underlying device %s is marked as "
7231                        "read-only. Setup failed\n", name, dev);
7232
7233                 GOTO(out_mnt, rc = -EROFS);
7234         }
7235
7236         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
7237                                         LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
7238                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
7239                 GOTO(out_mnt, rc = -EINVAL);
7240         }
7241
7242 #ifdef LDISKFS_MOUNT_DIRDATA
7243         if (LDISKFS_HAS_INCOMPAT_FEATURE(o->od_mnt->mnt_sb,
7244                                          LDISKFS_FEATURE_INCOMPAT_DIRDATA))
7245                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
7246         else if (strstr(name, "MDT")) /* don't complain for MGT or OSTs */
7247                 CWARN("%s: device %s was upgraded from Lustre-1.x without "
7248                       "enabling the dirdata feature. If you do not want to "
7249                       "downgrade to Lustre-1.x again, you can enable it via "
7250                       "'tune2fs -O dirdata device'\n", name, dev);
7251 #endif
7252         inode = osd_sb(o)->s_root->d_inode;
7253         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
7254         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
7255         if (rc != 0) {
7256                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
7257                 GOTO(out_mnt, rc);
7258         }
7259
7260         if (lmd_flags & LMD_FLG_NOSCRUB)
7261                 o->od_auto_scrub_interval = AS_NEVER;
7262
7263         GOTO(out, rc = 0);
7264
7265 out_mnt:
7266         mntput(o->od_mnt);
7267         o->od_mnt = NULL;
7268
7269 out:
7270         if (__page)
7271                 __free_page(__page);
7272
7273         return rc;
7274 }
7275
7276 static struct lu_device *osd_device_fini(const struct lu_env *env,
7277                                          struct lu_device *d)
7278 {
7279         struct osd_device *o = osd_dev(d);
7280         ENTRY;
7281
7282         osd_shutdown(env, o);
7283         osd_procfs_fini(o);
7284         osd_obj_map_fini(o);
7285         osd_umount(env, o);
7286
7287         RETURN(NULL);
7288 }
7289
7290 static int osd_device_init0(const struct lu_env *env,
7291                             struct osd_device *o,
7292                             struct lustre_cfg *cfg)
7293 {
7294         struct lu_device        *l = osd2lu_dev(o);
7295         struct osd_thread_info *info;
7296         int                     rc;
7297         int                     cplen = 0;
7298
7299         /* if the module was re-loaded, env can loose its keys */
7300         rc = lu_env_refill((struct lu_env *) env);
7301         if (rc)
7302                 GOTO(out, rc);
7303         info = osd_oti_get(env);
7304         LASSERT(info);
7305
7306         l->ld_ops = &osd_lu_ops;
7307         o->od_dt_dev.dd_ops = &osd_dt_ops;
7308
7309         spin_lock_init(&o->od_osfs_lock);
7310         mutex_init(&o->od_otable_mutex);
7311         INIT_LIST_HEAD(&o->od_orphan_list);
7312         INIT_LIST_HEAD(&o->od_index_backup_list);
7313         INIT_LIST_HEAD(&o->od_index_restore_list);
7314         spin_lock_init(&o->od_lock);
7315         o->od_index_backup_policy = LIBP_NONE;
7316
7317         o->od_read_cache = 1;
7318         o->od_writethrough_cache = 1;
7319         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
7320         o->od_auto_scrub_interval = AS_DEFAULT;
7321
7322         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
7323                         sizeof(o->od_svname));
7324         if (cplen >= sizeof(o->od_svname)) {
7325                 rc = -E2BIG;
7326                 GOTO(out, rc);
7327         }
7328
7329         o->od_index_backup_stop = 0;
7330         o->od_index = -1; /* -1 means index is invalid */
7331         rc = server_name2index(o->od_svname, &o->od_index, NULL);
7332         if (rc == LDD_F_SV_TYPE_OST)
7333                 o->od_is_ost = 1;
7334
7335         o->od_full_scrub_ratio = OFSR_DEFAULT;
7336         o->od_full_scrub_threshold_rate = FULL_SCRUB_THRESHOLD_RATE_DEFAULT;
7337         rc = osd_mount(env, o, cfg);
7338         if (rc != 0)
7339                 GOTO(out, rc);
7340
7341         rc = osd_obj_map_init(env, o);
7342         if (rc != 0)
7343                 GOTO(out_mnt, rc);
7344
7345         rc = lu_site_init(&o->od_site, l);
7346         if (rc != 0)
7347                 GOTO(out_compat, rc);
7348         o->od_site.ls_bottom_dev = l;
7349
7350         rc = lu_site_init_finish(&o->od_site);
7351         if (rc != 0)
7352                 GOTO(out_site, rc);
7353
7354         INIT_LIST_HEAD(&o->od_ios_list);
7355         /* setup scrub, including OI files initialization */
7356         o->od_in_init = 1;
7357         rc = osd_scrub_setup(env, o);
7358         o->od_in_init = 0;
7359         if (rc < 0)
7360                 GOTO(out_site, rc);
7361
7362         rc = osd_procfs_init(o, o->od_svname);
7363         if (rc != 0) {
7364                 CERROR("%s: can't initialize procfs: rc = %d\n",
7365                        o->od_svname, rc);
7366                 GOTO(out_scrub, rc);
7367         }
7368
7369         LASSERT(l->ld_site->ls_linkage.next != NULL);
7370         LASSERT(l->ld_site->ls_linkage.prev != NULL);
7371
7372         /* initialize quota slave instance */
7373         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
7374                                      o->od_proc_entry);
7375         if (IS_ERR(o->od_quota_slave)) {
7376                 rc = PTR_ERR(o->od_quota_slave);
7377                 o->od_quota_slave = NULL;
7378                 GOTO(out_procfs, rc);
7379         }
7380
7381         RETURN(0);
7382
7383 out_procfs:
7384         osd_procfs_fini(o);
7385 out_scrub:
7386         osd_scrub_cleanup(env, o);
7387 out_site:
7388         lu_site_fini(&o->od_site);
7389 out_compat:
7390         osd_obj_map_fini(o);
7391 out_mnt:
7392         osd_umount(env, o);
7393 out:
7394         return rc;
7395 }
7396
7397 static struct lu_device *osd_device_alloc(const struct lu_env *env,
7398                                           struct lu_device_type *t,
7399                                           struct lustre_cfg *cfg)
7400 {
7401         struct osd_device *o;
7402         int                rc;
7403
7404         OBD_ALLOC_PTR(o);
7405         if (o == NULL)
7406                 return ERR_PTR(-ENOMEM);
7407
7408         rc = dt_device_init(&o->od_dt_dev, t);
7409         if (rc == 0) {
7410                 /* Because the ctx might be revived in dt_device_init,
7411                  * refill the env here */
7412                 lu_env_refill((struct lu_env *)env);
7413                 rc = osd_device_init0(env, o, cfg);
7414                 if (rc)
7415                         dt_device_fini(&o->od_dt_dev);
7416         }
7417
7418         if (unlikely(rc != 0))
7419                 OBD_FREE_PTR(o);
7420
7421         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
7422 }
7423
7424 static struct lu_device *osd_device_free(const struct lu_env *env,
7425                                          struct lu_device *d)
7426 {
7427         struct osd_device *o = osd_dev(d);
7428         ENTRY;
7429
7430         /* XXX: make osd top device in order to release reference */
7431         d->ld_site->ls_top_dev = d;
7432         lu_site_purge(env, d->ld_site, -1);
7433         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
7434                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
7435                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
7436         }
7437         lu_site_fini(&o->od_site);
7438         dt_device_fini(&o->od_dt_dev);
7439         OBD_FREE_PTR(o);
7440         RETURN(NULL);
7441 }
7442
7443 static int osd_process_config(const struct lu_env *env,
7444                               struct lu_device *d, struct lustre_cfg *cfg)
7445 {
7446         struct osd_device               *o = osd_dev(d);
7447         int                             rc;
7448         ENTRY;
7449
7450         switch (cfg->lcfg_command) {
7451         case LCFG_SETUP:
7452                 rc = osd_mount(env, o, cfg);
7453                 break;
7454         case LCFG_CLEANUP:
7455                 /* For the case LCFG_PRE_CLEANUP is not called in advance,
7456                  * that may happend if hit failure during mount process. */
7457                 osd_index_backup(env, o, false);
7458                 lu_dev_del_linkage(d->ld_site, d);
7459                 rc = osd_shutdown(env, o);
7460                 break;
7461         case LCFG_PARAM:
7462                 LASSERT(&o->od_dt_dev);
7463                 rc = class_process_proc_param(PARAM_OSD, lprocfs_osd_obd_vars,
7464                                               cfg, &o->od_dt_dev);
7465                 if (rc > 0 || rc == -ENOSYS) {
7466                         rc = class_process_proc_param(PARAM_OST,
7467                                                       lprocfs_osd_obd_vars,
7468                                                       cfg, &o->od_dt_dev);
7469                         if (rc > 0)
7470                                 rc = 0;
7471                 }
7472                 break;
7473         case LCFG_PRE_CLEANUP:
7474                 osd_index_backup(env, o,
7475                                  o->od_index_backup_policy != LIBP_NONE);
7476                 rc = 0;
7477                 break;
7478         default:
7479                 rc = -ENOSYS;
7480         }
7481
7482         RETURN(rc);
7483 }
7484
7485 static int osd_recovery_complete(const struct lu_env *env,
7486                                  struct lu_device *d)
7487 {
7488         struct osd_device       *osd = osd_dev(d);
7489         int                      rc = 0;
7490         ENTRY;
7491
7492         if (osd->od_quota_slave == NULL)
7493                 RETURN(0);
7494
7495         /* start qsd instance on recovery completion, this notifies the quota
7496          * slave code that we are about to process new requests now */
7497         rc = qsd_start(env, osd->od_quota_slave);
7498         RETURN(rc);
7499 }
7500
7501 /*
7502  * we use exports to track all osd users
7503  */
7504 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
7505                            struct obd_device *obd, struct obd_uuid *cluuid,
7506                            struct obd_connect_data *data, void *localdata)
7507 {
7508         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
7509         struct lustre_handle  conn;
7510         int                   rc;
7511         ENTRY;
7512
7513         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
7514
7515         rc = class_connect(&conn, obd, cluuid);
7516         if (rc)
7517                 RETURN(rc);
7518
7519         *exp = class_conn2export(&conn);
7520
7521         spin_lock(&osd->od_osfs_lock);
7522         osd->od_connects++;
7523         spin_unlock(&osd->od_osfs_lock);
7524
7525         RETURN(0);
7526 }
7527
7528 /*
7529  * once last export (we don't count self-export) disappeared
7530  * osd can be released
7531  */
7532 static int osd_obd_disconnect(struct obd_export *exp)
7533 {
7534         struct obd_device *obd = exp->exp_obd;
7535         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
7536         int                rc, release = 0;
7537         ENTRY;
7538
7539         /* Only disconnect the underlying layers on the final disconnect. */
7540         spin_lock(&osd->od_osfs_lock);
7541         osd->od_connects--;
7542         if (osd->od_connects == 0)
7543                 release = 1;
7544         spin_unlock(&osd->od_osfs_lock);
7545
7546         rc = class_disconnect(exp); /* bz 9811 */
7547
7548         if (rc == 0 && release)
7549                 class_manual_cleanup(obd);
7550         RETURN(rc);
7551 }
7552
7553 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
7554                        struct lu_device *dev)
7555 {
7556         struct osd_device       *osd    = osd_dev(dev);
7557         struct lr_server_data   *lsd    =
7558                         &osd->od_dt_dev.dd_lu_dev.ld_site->ls_tgt->lut_lsd;
7559         int                      result = 0;
7560         ENTRY;
7561
7562         if (osd->od_quota_slave != NULL) {
7563                 /* set up quota slave objects */
7564                 result = qsd_prepare(env, osd->od_quota_slave);
7565                 if (result != 0)
7566                         RETURN(result);
7567         }
7568
7569         if (lsd->lsd_feature_incompat & OBD_COMPAT_OST) {
7570 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 52, 0)
7571                 if (lsd->lsd_feature_rocompat & OBD_ROCOMPAT_IDX_IN_IDIF) {
7572                         osd->od_index_in_idif = 1;
7573                 } else {
7574                         osd->od_index_in_idif = 0;
7575                         result = osd_register_proc_index_in_idif(osd);
7576                         if (result != 0)
7577                                 RETURN(result);
7578                 }
7579 #else
7580                 osd->od_index_in_idif = 1;
7581 #endif
7582         }
7583
7584         result = osd_fid_init(env, osd);
7585
7586         RETURN(result);
7587 }
7588
7589 static int osd_fid_alloc(const struct lu_env *env, struct obd_export *exp,
7590                          struct lu_fid *fid, struct md_op_data *op_data)
7591 {
7592         struct osd_device *osd = osd_dev(exp->exp_obd->obd_lu_dev);
7593
7594         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
7595 }
7596
7597 static const struct lu_object_operations osd_lu_obj_ops = {
7598         .loo_object_init      = osd_object_init,
7599         .loo_object_delete    = osd_object_delete,
7600         .loo_object_release   = osd_object_release,
7601         .loo_object_free      = osd_object_free,
7602         .loo_object_print     = osd_object_print,
7603         .loo_object_invariant = osd_object_invariant
7604 };
7605
7606 const struct lu_device_operations osd_lu_ops = {
7607         .ldo_object_alloc      = osd_object_alloc,
7608         .ldo_process_config    = osd_process_config,
7609         .ldo_recovery_complete = osd_recovery_complete,
7610         .ldo_prepare           = osd_prepare,
7611 };
7612
7613 static const struct lu_device_type_operations osd_device_type_ops = {
7614         .ldto_init = osd_type_init,
7615         .ldto_fini = osd_type_fini,
7616
7617         .ldto_start = osd_type_start,
7618         .ldto_stop  = osd_type_stop,
7619
7620         .ldto_device_alloc = osd_device_alloc,
7621         .ldto_device_free  = osd_device_free,
7622
7623         .ldto_device_init    = osd_device_init,
7624         .ldto_device_fini    = osd_device_fini
7625 };
7626
7627 static struct lu_device_type osd_device_type = {
7628         .ldt_tags     = LU_DEVICE_DT,
7629         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
7630         .ldt_ops      = &osd_device_type_ops,
7631         .ldt_ctx_tags = LCT_LOCAL,
7632 };
7633
7634 static int osd_health_check(const struct lu_env *env, struct obd_device *obd)
7635 {
7636         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
7637         struct super_block *sb = osd_sb(osd);
7638
7639         return (osd->od_mnt == NULL || sb->s_flags & MS_RDONLY);
7640 }
7641
7642 /*
7643  * lprocfs legacy support.
7644  */
7645 static struct obd_ops osd_obd_device_ops = {
7646         .o_owner = THIS_MODULE,
7647         .o_connect      = osd_obd_connect,
7648         .o_disconnect   = osd_obd_disconnect,
7649         .o_fid_alloc    = osd_fid_alloc,
7650         .o_health_check = osd_health_check,
7651 };
7652
7653 static int __init osd_init(void)
7654 {
7655         int rc;
7656
7657         CLASSERT(BH_DXLock < sizeof(((struct buffer_head *)0)->b_state) * 8);
7658 #if !defined(CONFIG_DEBUG_MUTEXES) && !defined(CONFIG_DEBUG_SPINLOCK)
7659         /* please, try to keep osd_thread_info smaller than a page */
7660         CLASSERT(sizeof(struct osd_thread_info) <= PAGE_SIZE);
7661 #endif
7662
7663         osd_oi_mod_init();
7664
7665         rc = lu_kmem_init(ldiskfs_caches);
7666         if (rc)
7667                 return rc;
7668
7669 #ifdef CONFIG_KALLSYMS
7670         priv_dev_set_rdonly = (void *)kallsyms_lookup_name("dev_set_rdonly");
7671         priv_dev_check_rdonly = (void *)kallsyms_lookup_name("dev_check_rdonly");
7672         /* Clear readonly is unused at this time */
7673         /*priv_dev_clear_rdonly = (void *)kallsyms_lookup_name("dev_clear_rdonly");*/
7674 #endif
7675
7676         rc = class_register_type(&osd_obd_device_ops, NULL, true,
7677                                  lprocfs_osd_module_vars,
7678                                  LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
7679         if (rc)
7680                 lu_kmem_fini(ldiskfs_caches);
7681         return rc;
7682 }
7683
7684 static void __exit osd_exit(void)
7685 {
7686         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
7687         lu_kmem_fini(ldiskfs_caches);
7688 }
7689
7690 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
7691 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
7692 MODULE_VERSION(LUSTRE_VERSION_STRING);
7693 MODULE_LICENSE("GPL");
7694
7695 module_init(osd_init);
7696 module_exit(osd_exit);