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