Whamcloud - gitweb
LU-4791 lod: subtract xattr overhead when calculate max EA size.
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osd/osd_handler.c
37  *
38  * Top-level entry points into osd module
39  *
40  * Author: Nikita Danilov <nikita@clusterfs.com>
41  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
42  */
43
44 #define DEBUG_SUBSYSTEM S_MDS
45
46 #include <linux/module.h>
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 /*
58  * struct OBD_{ALLOC,FREE}*()
59  * OBD_FAIL_CHECK
60  */
61 #include <obd_support.h>
62 /* struct ptlrpc_thread */
63 #include <lustre_net.h>
64 #include <lustre_fid.h>
65 /* process_config */
66 #include <lustre_param.h>
67
68 #include "osd_internal.h"
69 #include "osd_dynlocks.h"
70
71 /* llo_* api support */
72 #include <md_object.h>
73 #include <lustre_quota.h>
74
75 #include <ldiskfs/xattr.h>
76
77 int ldiskfs_pdo = 1;
78 CFS_MODULE_PARM(ldiskfs_pdo, "i", int, 0644,
79                 "ldiskfs with parallel directory operations");
80
81 int ldiskfs_track_declares_assert;
82 CFS_MODULE_PARM(ldiskfs_track_declares_assert, "i", int, 0644,
83                 "LBUG during tracking of declares");
84
85 /* Slab to allocate dynlocks */
86 struct kmem_cache *dynlock_cachep;
87
88 static struct lu_kmem_descr ldiskfs_caches[] = {
89         {
90                 .ckd_cache = &dynlock_cachep,
91                 .ckd_name  = "dynlock_cache",
92                 .ckd_size  = sizeof(struct dynlock_handle)
93         },
94         {
95                 .ckd_cache = NULL
96         }
97 };
98
99 static const char dot[] = ".";
100 static const char dotdot[] = "..";
101 static const char remote_obj_dir[] = "REM_OBJ_DIR";
102
103 static const struct lu_object_operations      osd_lu_obj_ops;
104 static const struct dt_object_operations      osd_obj_ops;
105 static const struct dt_object_operations      osd_obj_ea_ops;
106 static const struct dt_object_operations      osd_obj_otable_it_ops;
107 static const struct dt_index_operations       osd_index_iam_ops;
108 static const struct dt_index_operations       osd_index_ea_ops;
109
110 int osd_trans_declare_op2rb[] = {
111         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
112         [OSD_OT_PUNCH]          = OSD_OT_MAX,
113         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
114         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
115         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
116         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
117         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
118         [OSD_OT_WRITE]          = OSD_OT_WRITE,
119         [OSD_OT_INSERT]         = OSD_OT_DELETE,
120         [OSD_OT_DELETE]         = OSD_OT_INSERT,
121         [OSD_OT_UPDATE]         = OSD_OT_MAX,
122         [OSD_OT_QUOTA]          = OSD_OT_MAX,
123 };
124
125 static int osd_has_index(const struct osd_object *obj)
126 {
127         return obj->oo_dt.do_index_ops != NULL;
128 }
129
130 static int osd_object_invariant(const struct lu_object *l)
131 {
132         return osd_invariant(osd_obj(l));
133 }
134
135 /*
136  * Concurrency: doesn't matter
137  */
138
139 /*
140  * Concurrency: doesn't matter
141  */
142 static int osd_write_locked(const struct lu_env *env, struct osd_object *o)
143 {
144         struct osd_thread_info *oti = osd_oti_get(env);
145         return oti->oti_w_locks > 0 && o->oo_owner == env;
146 }
147
148 /*
149  * Concurrency: doesn't access mutable data
150  */
151 static int osd_root_get(const struct lu_env *env,
152                         struct dt_device *dev, struct lu_fid *f)
153 {
154         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
155         return 0;
156 }
157
158 /*
159  * OSD object methods.
160  */
161
162 /*
163  * Concurrency: no concurrent access is possible that early in object
164  * life-cycle.
165  */
166 static struct lu_object *osd_object_alloc(const struct lu_env *env,
167                                           const struct lu_object_header *hdr,
168                                           struct lu_device *d)
169 {
170         struct osd_object *mo;
171
172         OBD_ALLOC_PTR(mo);
173         if (mo != NULL) {
174                 struct lu_object *l;
175
176                 l = &mo->oo_dt.do_lu;
177                 dt_object_init(&mo->oo_dt, NULL, d);
178                 mo->oo_dt.do_ops = &osd_obj_ea_ops;
179                 l->lo_ops = &osd_lu_obj_ops;
180                 init_rwsem(&mo->oo_sem);
181                 init_rwsem(&mo->oo_ext_idx_sem);
182                 spin_lock_init(&mo->oo_guard);
183                 return l;
184         } else {
185                 return NULL;
186         }
187 }
188
189 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
190                 struct dentry *dentry, struct lustre_mdt_attrs *lma)
191 {
192         int rc;
193
194         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
195         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
196                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
197         if (rc > 0) {
198                 if ((void *)lma != (void *)info->oti_mdt_attrs_old)
199                         memcpy(lma, info->oti_mdt_attrs_old, sizeof(*lma));
200                 rc = 0;
201                 lustre_lma_swab(lma);
202                 /* Check LMA compatibility */
203                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
204                         CWARN("%.16s: unsupported incompat LMA feature(s) %#x "
205                               "for fid = "DFID", ino = %lu\n",
206                               LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
207                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
208                               PFID(&lma->lma_self_fid), inode->i_ino);
209                         rc = -EOPNOTSUPP;
210                 }
211         } else if (rc == 0) {
212                 rc = -ENODATA;
213         }
214
215         return rc;
216 }
217
218 /*
219  * retrieve object from backend ext fs.
220  **/
221 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
222                        struct osd_inode_id *id)
223 {
224         struct inode *inode = NULL;
225
226         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
227         if (IS_ERR(inode)) {
228                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
229                        id->oii_ino, PTR_ERR(inode));
230         } else if (id->oii_gen != OSD_OII_NOGEN &&
231                    inode->i_generation != id->oii_gen) {
232                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
233                        "i_generation = %u\n",
234                        id->oii_ino, id->oii_gen, inode->i_generation);
235                 iput(inode);
236                 inode = ERR_PTR(-ESTALE);
237         } else if (inode->i_nlink == 0) {
238                 /* due to parallel readdir and unlink,
239                 * we can have dead inode here. */
240                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
241                 iput(inode);
242                 inode = ERR_PTR(-ESTALE);
243         } else if (is_bad_inode(inode)) {
244                 CWARN("%.16s: bad inode: ino = %u\n",
245                 LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, id->oii_ino);
246                 iput(inode);
247                 inode = ERR_PTR(-ENOENT);
248         } else {
249                 if (id->oii_gen == OSD_OII_NOGEN)
250                         osd_id_gen(id, inode->i_ino, inode->i_generation);
251
252                 /* Do not update file c/mtime in ldiskfs.
253                  * NB: we don't have any lock to protect this because we don't
254                  * have reference on osd_object now, but contention with
255                  * another lookup + attr_set can't happen in the tiny window
256                  * between if (...) and set S_NOCMTIME. */
257                 if (!(inode->i_flags & S_NOCMTIME))
258                         inode->i_flags |= S_NOCMTIME;
259         }
260         return inode;
261 }
262
263 static struct inode *
264 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
265              struct osd_inode_id *id, struct lu_fid *fid)
266 {
267         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
268         struct inode            *inode;
269         int                      rc;
270
271         inode = osd_iget(info, dev, id);
272         if (IS_ERR(inode))
273                 return inode;
274
275         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
276         if (rc == 0) {
277                 *fid = lma->lma_self_fid;
278         } else if (rc == -ENODATA) {
279                 if (unlikely(inode == osd_sb(dev)->s_root->d_inode))
280                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
281                 else
282                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
283         } else {
284                 iput(inode);
285                 inode = ERR_PTR(rc);
286         }
287         return inode;
288 }
289
290 static struct inode *osd_iget_check(struct osd_thread_info *info,
291                                     struct osd_device *dev,
292                                     const struct lu_fid *fid,
293                                     struct osd_inode_id *id,
294                                     bool in_oi)
295 {
296         struct inode    *inode;
297         int              rc     = 0;
298         ENTRY;
299
300         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
301         if (IS_ERR(inode)) {
302                 rc = PTR_ERR(inode);
303                 if (!in_oi || (rc != -ENOENT && rc != -ESTALE)) {
304                         CDEBUG(D_INODE, "no inode: ino = %u, rc = %d\n",
305                                id->oii_ino, rc);
306
307                         GOTO(put, rc);
308                 }
309
310                 goto check_oi;
311         }
312
313         if (is_bad_inode(inode)) {
314                 rc = -ENOENT;
315                 if (!in_oi) {
316                         CDEBUG(D_INODE, "bad inode: ino = %u\n", id->oii_ino);
317
318                         GOTO(put, rc);
319                 }
320
321                 goto check_oi;
322         }
323
324         if (id->oii_gen != OSD_OII_NOGEN &&
325             inode->i_generation != id->oii_gen) {
326                 rc = -ESTALE;
327                 if (!in_oi) {
328                         CDEBUG(D_INODE, "unmatched inode: ino = %u, "
329                                "oii_gen = %u, i_generation = %u\n",
330                                id->oii_ino, id->oii_gen, inode->i_generation);
331
332                         GOTO(put, rc);
333                 }
334
335                 goto check_oi;
336         }
337
338         if (inode->i_nlink == 0) {
339                 rc = -ENOENT;
340                 if (!in_oi) {
341                         CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
342
343                         GOTO(put, rc);
344                 }
345
346                 goto check_oi;
347         }
348
349 check_oi:
350         if (rc != 0) {
351                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
352
353                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
354                 /* XXX: There are some possible cases:
355                  *      1. rc = 0.
356                  *         Backup/restore caused the OI invalid.
357                  *      2. rc = 0.
358                  *         Someone unlinked the object but NOT removed
359                  *         the OI mapping, such as mount target device
360                  *         as ldiskfs, and modify something directly.
361                  *      3. rc = -ENOENT.
362                  *         Someone just removed the object between the
363                  *         former oi_lookup and the iget. It is normal.
364                  *      4. Other failure cases.
365                  *
366                  *      Generally, when the device is mounted, it will
367                  *      auto check whether the system is restored from
368                  *      file-level backup or not. We trust such detect
369                  *      to distinguish the 1st case from the 2nd case. */
370                 if (rc == 0) {
371                         if (!IS_ERR(inode) && inode->i_generation != 0 &&
372                             inode->i_generation == id->oii_gen)
373                                 rc = -ENOENT;
374                         else
375                                 rc = -EREMCHG;
376                 }
377         } else {
378                 if (id->oii_gen == OSD_OII_NOGEN)
379                         osd_id_gen(id, inode->i_ino, inode->i_generation);
380
381                 /* Do not update file c/mtime in ldiskfs.
382                  * NB: we don't have any lock to protect this because we don't
383                  * have reference on osd_object now, but contention with
384                  * another lookup + attr_set can't happen in the tiny window
385                  * between if (...) and set S_NOCMTIME. */
386                 if (!(inode->i_flags & S_NOCMTIME))
387                         inode->i_flags |= S_NOCMTIME;
388         }
389
390         GOTO(put, rc);
391
392 put:
393         if (rc != 0) {
394                 if (!IS_ERR(inode))
395                         iput(inode);
396
397                 inode = ERR_PTR(rc);
398         }
399
400         return inode;
401 }
402
403 /**
404  * \retval +v: new filter_fid, does not contain self-fid
405  * \retval 0:  filter_fid_old, contains self-fid
406  * \retval -v: other failure cases
407  */
408 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
409                  struct dentry *dentry, struct lu_fid *fid)
410 {
411         struct filter_fid_old   *ff     = &info->oti_ff;
412         struct ost_id           *ostid  = &info->oti_ostid;
413         int                      rc;
414
415         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
416         if (rc == sizeof(*ff)) {
417                 rc = 0;
418                 ostid_set_seq(ostid, le64_to_cpu(ff->ff_seq));
419                 ostid_set_id(ostid, le64_to_cpu(ff->ff_objid));
420                 /* XXX: should use real OST index in the future. LU-3569 */
421                 ostid_to_fid(fid, ostid, 0);
422         } else if (rc == sizeof(struct filter_fid)) {
423                 rc = 1;
424         } else if (rc >= 0) {
425                 rc = -EINVAL;
426         }
427
428         return rc;
429 }
430
431 static int osd_lma_self_repair(struct osd_thread_info *info,
432                                struct osd_device *osd, struct inode *inode,
433                                const struct lu_fid *fid, __u32 compat)
434 {
435         handle_t *jh;
436         int       rc;
437
438         LASSERT(current->journal_info == NULL);
439
440         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
441                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
442         if (IS_ERR(jh)) {
443                 rc = PTR_ERR(jh);
444                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
445                       osd_name(osd), rc);
446                 return rc;
447         }
448
449         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
450         if (rc != 0)
451                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
452                       osd_name(osd), rc);
453         ldiskfs_journal_stop(jh);
454         return rc;
455 }
456
457 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
458 {
459         struct osd_thread_info  *info   = osd_oti_get(env);
460         struct osd_device       *osd    = osd_obj2dev(obj);
461         struct lustre_mdt_attrs *lma    = &info->oti_mdt_attrs;
462         struct inode            *inode  = obj->oo_inode;
463         struct dentry           *dentry = &info->oti_obj_dentry;
464         struct lu_fid           *fid    = NULL;
465         const struct lu_fid     *rfid   = lu_object_fid(&obj->oo_dt.do_lu);
466         int                      rc;
467         ENTRY;
468
469         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_COMPAT_INVALID_ENTRY))
470                 RETURN(0);
471
472         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
473         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
474                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
475         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
476                 fid = &lma->lma_self_fid;
477                 rc = osd_get_idif(info, inode, dentry, fid);
478                 if ((rc > 0) || (rc == -ENODATA && osd->od_lma_self_repair)) {
479                         /* For the given OST-object, if it has neither LMA nor
480                          * FID in XATTR_NAME_FID, then the given FID (which is
481                          * contained in the @obj, from client RPC for locating
482                          * the OST-object) is trusted. We use it to generate
483                          * the LMA. */
484                         osd_lma_self_repair(info, osd, inode, rfid,
485                                 fid_is_on_ost(info, osd, fid, OI_CHECK_FLD) ?
486                                 LMAC_FID_ON_OST : 0);
487                         RETURN(0);
488                 }
489         }
490
491         if (unlikely(rc == -ENODATA))
492                 RETURN(0);
493
494         if (rc < 0)
495                 RETURN(rc);
496
497         if (rc > 0) {
498                 rc = 0;
499                 lustre_lma_swab(lma);
500                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
501                              CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT))) {
502                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
503                               "fid = "DFID", ino = %lu\n", osd_name(osd),
504                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
505                               PFID(rfid), inode->i_ino);
506                         rc = -EOPNOTSUPP;
507                 } else if (!(lma->lma_compat & LMAC_NOT_IN_OI)) {
508                         fid = &lma->lma_self_fid;
509                 }
510         }
511
512         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
513                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
514                         struct ost_id   *oi   = &info->oti_ostid;
515                         struct lu_fid   *fid1 = &info->oti_fid3;
516                         __u32            idx  = fid_idif_ost_idx(rfid);
517
518                         /* For old IDIF, the OST index is not part of the IDIF,
519                          * Means that different OSTs may have the same IDIFs.
520                          * Under such case, we need to make some compatible
521                          * check to make sure to trigger OI scrub properly. */
522                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
523                                 /* Given @rfid is new, LMA is old. */
524                                 fid_to_ostid(fid, oi);
525                                 ostid_to_fid(fid1, oi, idx);
526                                 if (lu_fid_eq(fid1, rfid)) {
527                                         if (osd->od_lma_self_repair)
528                                                 osd_lma_self_repair(info, osd,
529                                                         inode, rfid,
530                                                         LMAC_FID_ON_OST);
531                                         RETURN(0);
532                                 }
533                         }
534                 }
535
536                 CDEBUG(D_INODE, "%s: FID "DFID" != self_fid "DFID"\n",
537                        osd_name(osd), PFID(rfid), PFID(fid));
538                 rc = -EREMCHG;
539         }
540
541         RETURN(rc);
542 }
543
544 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
545                           const struct lu_fid *fid,
546                           const struct lu_object_conf *conf)
547 {
548         struct osd_thread_info *info;
549         struct lu_device       *ldev   = obj->oo_dt.do_lu.lo_dev;
550         struct osd_device      *dev;
551         struct osd_idmap_cache *oic;
552         struct osd_inode_id    *id;
553         struct inode           *inode;
554         struct osd_scrub       *scrub;
555         struct scrub_file      *sf;
556         int                     result;
557         int                     saved  = 0;
558         bool                    in_oi  = false;
559         bool                    triggered = false;
560         ENTRY;
561
562         LINVRNT(osd_invariant(obj));
563         LASSERT(obj->oo_inode == NULL);
564         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID, PFID(fid));
565
566         dev = osd_dev(ldev);
567         scrub = &dev->od_scrub;
568         sf = &scrub->os_file;
569         info = osd_oti_get(env);
570         LASSERT(info);
571         oic = &info->oti_cache;
572
573         if (OBD_FAIL_CHECK(OBD_FAIL_OST_ENOENT))
574                 RETURN(-ENOENT);
575
576         /* For the object is created as locking anchor, or for the object to
577          * be created on disk. No need to osd_oi_lookup() at here because FID
578          * shouldn't never be re-used, if it's really a duplicate FID from
579          * unexpected reason, we should be able to detect it later by calling
580          * do_create->osd_oi_insert(). */
581         if (conf != NULL && conf->loc_flags & LOC_F_NEW)
582                 GOTO(out, result = 0);
583
584         /* Search order: 1. per-thread cache. */
585         if (lu_fid_eq(fid, &oic->oic_fid) &&
586             likely(oic->oic_dev == dev)) {
587                 id = &oic->oic_lid;
588                 goto iget;
589         }
590
591         id = &info->oti_id;
592         if (!cfs_list_empty(&scrub->os_inconsistent_items)) {
593                 /* Search order: 2. OI scrub pending list. */
594                 result = osd_oii_lookup(dev, fid, id);
595                 if (result == 0)
596                         goto iget;
597         }
598
599         /* Search order: 3. OI files. */
600         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
601         if (result == -ENOENT) {
602                 if (!fid_is_norm(fid) ||
603                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
604                     !ldiskfs_test_bit(osd_oi_fid2idx(dev,fid),
605                                       sf->sf_oi_bitmap))
606                         GOTO(out, result = 0);
607
608                 goto trigger;
609         }
610
611         if (result != 0)
612                 GOTO(out, result);
613
614         in_oi = true;
615
616 iget:
617         inode = osd_iget_check(info, dev, fid, id, in_oi);
618         if (IS_ERR(inode)) {
619                 result = PTR_ERR(inode);
620                 if (result == -ENOENT || result == -ESTALE) {
621                         if (!in_oi)
622                                 fid_zero(&oic->oic_fid);
623
624                         GOTO(out, result = -ENOENT);
625                 } else if (result == -EREMCHG) {
626
627 trigger:
628                         if (!in_oi)
629                                 fid_zero(&oic->oic_fid);
630
631                         if (unlikely(triggered))
632                                 GOTO(out, result = saved);
633
634                         triggered = true;
635                         if (thread_is_running(&scrub->os_thread)) {
636                                 result = -EINPROGRESS;
637                         } else if (!dev->od_noscrub) {
638                                 result = osd_scrub_start(dev);
639                                 LCONSOLE_WARN("%.16s: trigger OI scrub by RPC "
640                                               "for "DFID", rc = %d [1]\n",
641                                               osd_name(dev), PFID(fid),result);
642                                 if (result == 0 || result == -EALREADY)
643                                         result = -EINPROGRESS;
644                                 else
645                                         result = -EREMCHG;
646                         }
647
648                         /* We still have chance to get the valid inode: for the
649                          * object which is referenced by remote name entry, the
650                          * object on the local MDT will be linked under the dir
651                          * of "/REMOTE_PARENT_DIR" with its FID string as name.
652                          *
653                          * We do not know whether the object for the given FID
654                          * is referenced by some remote name entry or not, and
655                          * especially for DNE II, a multiple-linked object may
656                          * have many name entries reside on many MDTs.
657                          *
658                          * To simplify the operation, OSD will not distinguish
659                          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
660                          * only happened for the RPC from other MDT during the
661                          * OI scrub, or for the client side RPC with FID only,
662                          * such as FID to path, or from old connected client. */
663                         saved = result;
664                         result = osd_lookup_in_remote_parent(info, dev,
665                                                              fid, id);
666                         if (result == 0) {
667                                 in_oi = false;
668                                 goto iget;
669                         }
670
671                         result = saved;
672                 }
673
674                 GOTO(out, result);
675         }
676
677         obj->oo_inode = inode;
678         LASSERT(obj->oo_inode->i_sb == osd_sb(dev));
679
680         result = osd_check_lma(env, obj);
681         if (result != 0) {
682                 iput(inode);
683                 obj->oo_inode = NULL;
684                 if (result == -EREMCHG) {
685                         if (!in_oi) {
686                                 result = osd_oi_lookup(info, dev, fid, id,
687                                                        OI_CHECK_FLD);
688                                 if (result != 0) {
689                                         fid_zero(&oic->oic_fid);
690                                         GOTO(out, result);
691                                 }
692                         }
693
694                         goto trigger;
695                 }
696
697                 GOTO(out, result);
698         }
699
700         obj->oo_compat_dot_created = 1;
701         obj->oo_compat_dotdot_created = 1;
702
703         if (!S_ISDIR(inode->i_mode) || !ldiskfs_pdo) /* done */
704                 GOTO(out, result = 0);
705
706         LASSERT(obj->oo_hl_head == NULL);
707         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
708         if (obj->oo_hl_head == NULL) {
709                 obj->oo_inode = NULL;
710                 iput(inode);
711                 GOTO(out, result = -ENOMEM);
712         }
713         GOTO(out, result = 0);
714
715 out:
716         LINVRNT(osd_invariant(obj));
717         return result;
718 }
719
720 /*
721  * Concurrency: shouldn't matter.
722  */
723 static void osd_object_init0(struct osd_object *obj)
724 {
725         LASSERT(obj->oo_inode != NULL);
726         obj->oo_dt.do_body_ops = &osd_body_ops;
727         obj->oo_dt.do_lu.lo_header->loh_attr |=
728                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
729 }
730
731 /*
732  * Concurrency: no concurrent access is possible that early in object
733  * life-cycle.
734  */
735 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
736                            const struct lu_object_conf *conf)
737 {
738         struct osd_object *obj = osd_obj(l);
739         int result;
740
741         LINVRNT(osd_invariant(obj));
742
743         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
744                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
745                 l->lo_header->loh_attr |= LOHA_EXISTS;
746                 return 0;
747         }
748
749         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
750         obj->oo_dt.do_body_ops = &osd_body_ops_new;
751         if (result == 0 && obj->oo_inode != NULL)
752                 osd_object_init0(obj);
753
754         LINVRNT(osd_invariant(obj));
755         return result;
756 }
757
758 /*
759  * Concurrency: no concurrent access is possible that late in object
760  * life-cycle.
761  */
762 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
763 {
764         struct osd_object *obj = osd_obj(l);
765
766         LINVRNT(osd_invariant(obj));
767
768         dt_object_fini(&obj->oo_dt);
769         if (obj->oo_hl_head != NULL)
770                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
771         OBD_FREE_PTR(obj);
772 }
773
774 /*
775  * Concurrency: no concurrent access is possible that late in object
776  * life-cycle.
777  */
778 static void osd_index_fini(struct osd_object *o)
779 {
780         struct iam_container *bag;
781
782         if (o->oo_dir != NULL) {
783                 bag = &o->oo_dir->od_container;
784                 if (o->oo_inode != NULL) {
785                         if (bag->ic_object == o->oo_inode)
786                                 iam_container_fini(bag);
787                 }
788                 OBD_FREE_PTR(o->oo_dir);
789                 o->oo_dir = NULL;
790         }
791 }
792
793 /*
794  * Concurrency: no concurrent access is possible that late in object
795  * life-cycle (for all existing callers, that is. New callers have to provide
796  * their own locking.)
797  */
798 static int osd_inode_unlinked(const struct inode *inode)
799 {
800         return inode->i_nlink == 0;
801 }
802
803 enum {
804         OSD_TXN_OI_DELETE_CREDITS    = 20,
805         OSD_TXN_INODE_DELETE_CREDITS = 20
806 };
807
808 /*
809  * Journal
810  */
811
812 #if OSD_THANDLE_STATS
813 /**
814  * Set time when the handle is allocated
815  */
816 static void osd_th_alloced(struct osd_thandle *oth)
817 {
818         oth->oth_alloced = cfs_time_current();
819 }
820
821 /**
822  * Set time when the handle started
823  */
824 static void osd_th_started(struct osd_thandle *oth)
825 {
826         oth->oth_started = cfs_time_current();
827 }
828
829 /**
830  * Helper function to convert time interval to microseconds packed in
831  * long int.
832  */
833 static long interval_to_usec(cfs_time_t start, cfs_time_t end)
834 {
835         struct timeval val;
836
837         cfs_duration_usec(cfs_time_sub(end, start), &val);
838         return val.tv_sec * 1000000 + val.tv_usec;
839 }
840
841 /**
842  * Check whether the we deal with this handle for too long.
843  */
844 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
845                                 cfs_time_t alloced, cfs_time_t started,
846                                 cfs_time_t closed)
847 {
848         cfs_time_t now = cfs_time_current();
849
850         LASSERT(dev != NULL);
851
852         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
853                             interval_to_usec(alloced, started));
854         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
855                             interval_to_usec(started, closed));
856         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
857                             interval_to_usec(closed, now));
858
859         if (cfs_time_before(cfs_time_add(alloced, cfs_time_seconds(30)), now)) {
860                 CWARN("transaction handle %p was open for too long: "
861                       "now "CFS_TIME_T" ,"
862                       "alloced "CFS_TIME_T" ,"
863                       "started "CFS_TIME_T" ,"
864                       "closed "CFS_TIME_T"\n",
865                       oth, now, alloced, started, closed);
866                 libcfs_debug_dumpstack(NULL);
867         }
868 }
869
870 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
871 {                                                                       \
872         cfs_time_t __closed = cfs_time_current();                       \
873         cfs_time_t __alloced = oth->oth_alloced;                        \
874         cfs_time_t __started = oth->oth_started;                        \
875                                                                         \
876         expr;                                                           \
877         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
878 }
879
880 #else /* OSD_THANDLE_STATS */
881
882 #define osd_th_alloced(h)                  do {} while(0)
883 #define osd_th_started(h)                  do {} while(0)
884 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
885
886 #endif /* OSD_THANDLE_STATS */
887
888 /*
889  * Concurrency: doesn't access mutable data.
890  */
891 static int osd_param_is_not_sane(const struct osd_device *dev,
892                                  const struct thandle *th)
893 {
894         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
895
896         return oh->ot_credits > osd_journal(dev)->j_max_transaction_buffers;
897 }
898
899 /*
900  * Concurrency: shouldn't matter.
901  */
902 static void osd_trans_commit_cb(struct super_block *sb,
903                                 struct ldiskfs_journal_cb_entry *jcb, int error)
904 {
905         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
906         struct thandle     *th  = &oh->ot_super;
907         struct lu_device   *lud = &th->th_dev->dd_lu_dev;
908         struct dt_txn_commit_cb *dcb, *tmp;
909
910         LASSERT(oh->ot_handle == NULL);
911
912         if (error)
913                 CERROR("transaction @0x%p commit error: %d\n", th, error);
914
915         dt_txn_hook_commit(th);
916
917         /* call per-transaction callbacks if any */
918         cfs_list_for_each_entry_safe(dcb, tmp, &oh->ot_dcb_list, dcb_linkage) {
919                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
920                          "commit callback entry: magic=%x name='%s'\n",
921                          dcb->dcb_magic, dcb->dcb_name);
922                 cfs_list_del_init(&dcb->dcb_linkage);
923                 dcb->dcb_func(NULL, th, dcb, error);
924         }
925
926         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
927         lu_device_put(lud);
928         th->th_dev = NULL;
929
930         lu_context_exit(&th->th_ctx);
931         lu_context_fini(&th->th_ctx);
932         thandle_put(th);
933 }
934
935 static struct thandle *osd_trans_create(const struct lu_env *env,
936                                         struct dt_device *d)
937 {
938         struct osd_thread_info  *oti = osd_oti_get(env);
939         struct osd_iobuf        *iobuf = &oti->oti_iobuf;
940         struct osd_thandle      *oh;
941         struct thandle          *th;
942         ENTRY;
943
944         /* on pending IO in this thread should left from prev. request */
945         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
946
947         th = ERR_PTR(-ENOMEM);
948         OBD_ALLOC_GFP(oh, sizeof *oh, GFP_NOFS);
949         if (oh != NULL) {
950                 oh->ot_quota_trans = &oti->oti_quota_trans;
951                 memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
952                 th = &oh->ot_super;
953                 th->th_dev = d;
954                 th->th_result = 0;
955                 th->th_tags = LCT_TX_HANDLE;
956                 oh->ot_credits = 0;
957                 atomic_set(&th->th_refc, 1);
958                 th->th_alloc_size = sizeof(*oh);
959                 oti->oti_dev = osd_dt_dev(d);
960                 CFS_INIT_LIST_HEAD(&oh->ot_dcb_list);
961                 osd_th_alloced(oh);
962
963                 memset(oti->oti_declare_ops, 0,
964                                         sizeof(oti->oti_declare_ops));
965                 memset(oti->oti_declare_ops_rb, 0,
966                                         sizeof(oti->oti_declare_ops_rb));
967                 memset(oti->oti_declare_ops_cred, 0,
968                                         sizeof(oti->oti_declare_ops_cred));
969                 oti->oti_rollback = false;
970         }
971         RETURN(th);
972 }
973
974 /*
975  * Concurrency: shouldn't matter.
976  */
977 int osd_trans_start(const struct lu_env *env, struct dt_device *d,
978                     struct thandle *th)
979 {
980         struct osd_thread_info *oti = osd_oti_get(env);
981         struct osd_device  *dev = osd_dt_dev(d);
982         handle_t           *jh;
983         struct osd_thandle *oh;
984         int rc;
985
986         ENTRY;
987
988         LASSERT(current->journal_info == NULL);
989
990         oh = container_of0(th, struct osd_thandle, ot_super);
991         LASSERT(oh != NULL);
992         LASSERT(oh->ot_handle == NULL);
993
994         rc = dt_txn_hook_start(env, d, th);
995         if (rc != 0)
996                 GOTO(out, rc);
997
998         if (unlikely(osd_param_is_not_sane(dev, th))) {
999                 static unsigned long last_printed;
1000                 static int last_credits;
1001
1002                 CWARN("%.16s: too many transaction credits (%d > %d)\n",
1003                       LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
1004                       oh->ot_credits,
1005                       osd_journal(dev)->j_max_transaction_buffers);
1006                 CWARN("  create: %u/%u, destroy: %u/%u\n",
1007                       oti->oti_declare_ops[OSD_OT_CREATE],
1008                       oti->oti_declare_ops_cred[OSD_OT_CREATE],
1009                       oti->oti_declare_ops[OSD_OT_DESTROY],
1010                       oti->oti_declare_ops_cred[OSD_OT_DESTROY]);
1011                 CWARN("  attr_set: %u/%u, xattr_set: %u/%u\n",
1012                       oti->oti_declare_ops[OSD_OT_ATTR_SET],
1013                       oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1014                       oti->oti_declare_ops[OSD_OT_XATTR_SET],
1015                       oti->oti_declare_ops_cred[OSD_OT_XATTR_SET]);
1016                 CWARN("  write: %u/%u, punch: %u/%u, quota %u/%u\n",
1017                       oti->oti_declare_ops[OSD_OT_WRITE],
1018                       oti->oti_declare_ops_cred[OSD_OT_WRITE],
1019                       oti->oti_declare_ops[OSD_OT_PUNCH],
1020                       oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1021                       oti->oti_declare_ops[OSD_OT_QUOTA],
1022                       oti->oti_declare_ops_cred[OSD_OT_QUOTA]);
1023                 CWARN("  insert: %u/%u, delete: %u/%u\n",
1024                       oti->oti_declare_ops[OSD_OT_INSERT],
1025                       oti->oti_declare_ops_cred[OSD_OT_INSERT],
1026                       oti->oti_declare_ops[OSD_OT_DELETE],
1027                       oti->oti_declare_ops_cred[OSD_OT_DELETE]);
1028                 CWARN("  ref_add: %u/%u, ref_del: %u/%u\n",
1029                       oti->oti_declare_ops[OSD_OT_REF_ADD],
1030                       oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1031                       oti->oti_declare_ops[OSD_OT_REF_DEL],
1032                       oti->oti_declare_ops_cred[OSD_OT_REF_DEL]);
1033
1034                 if (last_credits != oh->ot_credits &&
1035                     time_after(jiffies, last_printed + 60 * HZ)) {
1036                         libcfs_debug_dumpstack(NULL);
1037                         last_credits = oh->ot_credits;
1038                         last_printed = jiffies;
1039                 }
1040                 /* XXX Limit the credits to 'max_transaction_buffers', and
1041                  *     let the underlying filesystem to catch the error if
1042                  *     we really need so many credits.
1043                  *
1044                  *     This should be removed when we can calculate the
1045                  *     credits precisely. */
1046                 oh->ot_credits = osd_journal(dev)->j_max_transaction_buffers;
1047         }
1048
1049         /*
1050          * XXX temporary stuff. Some abstraction layer should
1051          * be used.
1052          */
1053         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
1054         osd_th_started(oh);
1055         if (!IS_ERR(jh)) {
1056                 oh->ot_handle = jh;
1057                 LASSERT(oti->oti_txns == 0);
1058                 lu_context_init(&th->th_ctx, th->th_tags);
1059                 lu_context_enter(&th->th_ctx);
1060
1061                 lu_device_get(&d->dd_lu_dev);
1062                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
1063                               "osd-tx", th);
1064                 oti->oti_txns++;
1065                 rc = 0;
1066         } else {
1067                 rc = PTR_ERR(jh);
1068         }
1069 out:
1070         RETURN(rc);
1071 }
1072
1073 static int osd_seq_exists(const struct lu_env *env,
1074                               struct osd_device *osd, obd_seq seq)
1075 {
1076         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
1077         struct seq_server_site  *ss = osd_seq_site(osd);
1078         int                     rc;
1079         ENTRY;
1080
1081         if (ss == NULL)
1082                 RETURN(1);
1083
1084         rc = osd_fld_lookup(env, osd, seq, range);
1085         if (rc != 0) {
1086                 if (rc != -ENOENT)
1087                         CERROR("%s: can't lookup FLD sequence "LPX64
1088                                ": rc = %d\n", osd_name(osd), seq, rc);
1089                 RETURN(0);
1090         }
1091
1092         RETURN(ss->ss_node_id == range->lsr_index);
1093 }
1094
1095 /*
1096  * Concurrency: shouldn't matter.
1097  */
1098 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
1099                           struct thandle *th)
1100 {
1101         int                     rc = 0;
1102         struct osd_thandle     *oh;
1103         struct osd_thread_info *oti = osd_oti_get(env);
1104         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
1105         struct qsd_instance    *qsd = oti->oti_dev->od_quota_slave;
1106         struct lquota_trans    *qtrans;
1107         ENTRY;
1108
1109         oh = container_of0(th, struct osd_thandle, ot_super);
1110
1111         qtrans = oh->ot_quota_trans;
1112         oh->ot_quota_trans = NULL;
1113
1114         if (oh->ot_handle != NULL) {
1115                 handle_t *hdl = oh->ot_handle;
1116
1117                 /*
1118                  * add commit callback
1119                  * notice we don't do this in osd_trans_start()
1120                  * as underlying transaction can change during truncate
1121                  */
1122                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
1123                                          &oh->ot_jcb);
1124
1125                 LASSERT(oti->oti_txns == 1);
1126                 oti->oti_txns--;
1127                 rc = dt_txn_hook_stop(env, th);
1128                 if (rc != 0)
1129                         CERROR("Failure in transaction hook: %d\n", rc);
1130
1131                 /* hook functions might modify th_sync */
1132                 hdl->h_sync = th->th_sync;
1133
1134                 oh->ot_handle = NULL;
1135                 OSD_CHECK_SLOW_TH(oh, oti->oti_dev,
1136                                   rc = ldiskfs_journal_stop(hdl));
1137                 if (rc != 0)
1138                         CERROR("Failure to stop transaction: %d\n", rc);
1139         } else {
1140                 thandle_put(&oh->ot_super);
1141         }
1142
1143         /* inform the quota slave device that the transaction is stopping */
1144         qsd_op_end(env, qsd, qtrans);
1145
1146         /* as we want IO to journal and data IO be concurrent, we don't block
1147          * awaiting data IO completion in osd_do_bio(), instead we wait here
1148          * once transaction is submitted to the journal. all reqular requests
1149          * don't do direct IO (except read/write), thus this wait_event becomes
1150          * no-op for them.
1151          *
1152          * IMPORTANT: we have to wait till any IO submited by the thread is
1153          * completed otherwise iobuf may be corrupted by different request
1154          */
1155         wait_event(iobuf->dr_wait,
1156                        atomic_read(&iobuf->dr_numreqs) == 0);
1157         if (!rc)
1158                 rc = iobuf->dr_error;
1159
1160         RETURN(rc);
1161 }
1162
1163 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
1164 {
1165         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
1166                                                ot_super);
1167
1168         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
1169         LASSERT(&dcb->dcb_func != NULL);
1170         cfs_list_add(&dcb->dcb_linkage, &oh->ot_dcb_list);
1171
1172         return 0;
1173 }
1174
1175 /*
1176  * Called just before object is freed. Releases all resources except for
1177  * object itself (that is released by osd_object_free()).
1178  *
1179  * Concurrency: no concurrent access is possible that late in object
1180  * life-cycle.
1181  */
1182 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
1183 {
1184         struct osd_object *obj   = osd_obj(l);
1185         struct inode      *inode = obj->oo_inode;
1186
1187         LINVRNT(osd_invariant(obj));
1188
1189         /*
1190          * If object is unlinked remove fid->ino mapping from object index.
1191          */
1192
1193         osd_index_fini(obj);
1194         if (inode != NULL) {
1195                 struct qsd_instance     *qsd = osd_obj2dev(obj)->od_quota_slave;
1196                 qid_t                    uid = inode->i_uid;
1197                 qid_t                    gid = inode->i_gid;
1198
1199                 iput(inode);
1200                 obj->oo_inode = NULL;
1201
1202                 if (qsd != NULL) {
1203                         struct osd_thread_info  *info = osd_oti_get(env);
1204                         struct lquota_id_info   *qi = &info->oti_qi;
1205
1206                         /* Release granted quota to master if necessary */
1207                         qi->lqi_id.qid_uid = uid;
1208                         qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
1209
1210                         qi->lqi_id.qid_uid = gid;
1211                         qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
1212                 }
1213         }
1214 }
1215
1216 /*
1217  * Concurrency: ->loo_object_release() is called under site spin-lock.
1218  */
1219 static void osd_object_release(const struct lu_env *env,
1220                                struct lu_object *l)
1221 {
1222 }
1223
1224 /*
1225  * Concurrency: shouldn't matter.
1226  */
1227 static int osd_object_print(const struct lu_env *env, void *cookie,
1228                             lu_printer_t p, const struct lu_object *l)
1229 {
1230         struct osd_object *o = osd_obj(l);
1231         struct iam_descr  *d;
1232
1233         if (o->oo_dir != NULL)
1234                 d = o->oo_dir->od_container.ic_descr;
1235         else
1236                 d = NULL;
1237         return (*p)(env, cookie,
1238                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
1239                     o, o->oo_inode,
1240                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
1241                     o->oo_inode ? o->oo_inode->i_generation : 0,
1242                     d ? d->id_ops->id_name : "plain");
1243 }
1244
1245 #define GRANT_FOR_LOCAL_OIDS 32 /* 128kB for last_rcvd, quota files, ... */
1246
1247 /*
1248  * Concurrency: shouldn't matter.
1249  */
1250 int osd_statfs(const struct lu_env *env, struct dt_device *d,
1251                struct obd_statfs *sfs)
1252 {
1253         struct osd_device  *osd = osd_dt_dev(d);
1254         struct super_block *sb = osd_sb(osd);
1255         struct kstatfs     *ksfs;
1256         int result = 0;
1257
1258         if (unlikely(osd->od_mnt == NULL))
1259                 return -EINPROGRESS;
1260
1261         /* osd_lproc.c call this without env, allocate ksfs for that case */
1262         if (unlikely(env == NULL)) {
1263                 OBD_ALLOC_PTR(ksfs);
1264                 if (ksfs == NULL)
1265                         return -ENOMEM;
1266         } else {
1267                 ksfs = &osd_oti_get(env)->oti_ksfs;
1268         }
1269
1270         spin_lock(&osd->od_osfs_lock);
1271         result = sb->s_op->statfs(sb->s_root, ksfs);
1272         if (likely(result == 0)) { /* N.B. statfs can't really fail */
1273                 statfs_pack(sfs, ksfs);
1274                 if (sb->s_flags & MS_RDONLY)
1275                         sfs->os_state = OS_STATE_READONLY;
1276         }
1277
1278         spin_unlock(&osd->od_osfs_lock);
1279
1280         if (unlikely(env == NULL))
1281                 OBD_FREE_PTR(ksfs);
1282
1283         /* Reserve a small amount of space for local objects like last_rcvd,
1284          * llog, quota files, ... */
1285         if (sfs->os_bavail <= GRANT_FOR_LOCAL_OIDS) {
1286                 sfs->os_bavail = 0;
1287         } else {
1288                 sfs->os_bavail -= GRANT_FOR_LOCAL_OIDS;
1289                 /** Take out metadata overhead for indirect blocks */
1290                 sfs->os_bavail -= sfs->os_bavail >> (sb->s_blocksize_bits - 3);
1291         }
1292
1293         return result;
1294 }
1295
1296 /**
1297  * Estimate space needed for file creations. We assume the largest filename
1298  * which is 2^64 - 1, hence a filename of 20 chars.
1299  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
1300  */
1301 #ifdef __LDISKFS_DIR_REC_LEN
1302 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
1303 #else
1304 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
1305 #endif
1306
1307 /*
1308  * Concurrency: doesn't access mutable data.
1309  */
1310 static void osd_conf_get(const struct lu_env *env,
1311                          const struct dt_device *dev,
1312                          struct dt_device_param *param)
1313 {
1314         struct super_block *sb = osd_sb(osd_dt_dev(dev));
1315         int                ea_overhead;
1316
1317         /*
1318          * XXX should be taken from not-yet-existing fs abstraction layer.
1319          */
1320         param->ddp_max_name_len = LDISKFS_NAME_LEN;
1321         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
1322         param->ddp_block_shift  = sb->s_blocksize_bits;
1323         param->ddp_mount_type     = LDD_MT_LDISKFS;
1324         param->ddp_maxbytes       = sb->s_maxbytes;
1325         /* Overhead estimate should be fairly accurate, so we really take a tiny
1326          * error margin which also avoids fragmenting the filesystem too much */
1327         param->ddp_grant_reserved = 2; /* end up to be 1.9% after conversion */
1328         /* inode are statically allocated, so per-inode space consumption
1329          * is the space consumed by the directory entry */
1330         param->ddp_inodespace     = PER_OBJ_USAGE;
1331         /* per-fragment overhead to be used by the client code */
1332         param->ddp_grant_frag     = 6 * LDISKFS_BLOCK_SIZE(sb);
1333         param->ddp_mntopts      = 0;
1334         if (test_opt(sb, XATTR_USER))
1335                 param->ddp_mntopts |= MNTOPT_USERXATTR;
1336         if (test_opt(sb, POSIX_ACL))
1337                 param->ddp_mntopts |= MNTOPT_ACL;
1338
1339         /* LOD might calculate the max stripe count based on max_ea_size,
1340          * so we need take account in the overhead as well,
1341          * xattr_header + magic + xattr_entry_head */
1342         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
1343                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
1344
1345 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
1346         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EA_INODE))
1347                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
1348                                                                 ea_overhead;
1349         else
1350 #endif
1351                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
1352 }
1353
1354 /*
1355  * Concurrency: shouldn't matter.
1356  */
1357 static int osd_sync(const struct lu_env *env, struct dt_device *d)
1358 {
1359         CDEBUG(D_HA, "syncing OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1360         return ldiskfs_force_commit(osd_sb(osd_dt_dev(d)));
1361 }
1362
1363 /**
1364  * Start commit for OSD device.
1365  *
1366  * An implementation of dt_commit_async method for OSD device.
1367  * Asychronously starts underlayng fs sync and thereby a transaction
1368  * commit.
1369  *
1370  * \param env environment
1371  * \param d dt device
1372  *
1373  * \see dt_device_operations
1374  */
1375 static int osd_commit_async(const struct lu_env *env,
1376                             struct dt_device *d)
1377 {
1378         struct super_block *s = osd_sb(osd_dt_dev(d));
1379         ENTRY;
1380
1381         CDEBUG(D_HA, "async commit OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1382         RETURN(s->s_op->sync_fs(s, 0));
1383 }
1384
1385 /*
1386  * Concurrency: shouldn't matter.
1387  */
1388
1389 static int osd_ro(const struct lu_env *env, struct dt_device *d)
1390 {
1391         struct super_block *sb = osd_sb(osd_dt_dev(d));
1392         struct block_device *dev = sb->s_bdev;
1393 #ifdef HAVE_DEV_SET_RDONLY
1394         struct block_device *jdev = LDISKFS_SB(sb)->journal_bdev;
1395         int rc = 0;
1396 #else
1397         int rc = -EOPNOTSUPP;
1398 #endif
1399         ENTRY;
1400
1401 #ifdef HAVE_DEV_SET_RDONLY
1402         CERROR("*** setting %s read-only ***\n", osd_dt_dev(d)->od_svname);
1403
1404         if (jdev && (jdev != dev)) {
1405                 CDEBUG(D_IOCTL | D_HA, "set journal dev %lx rdonly\n",
1406                        (long)jdev);
1407                 dev_set_rdonly(jdev);
1408         }
1409         CDEBUG(D_IOCTL | D_HA, "set dev %lx rdonly\n", (long)dev);
1410         dev_set_rdonly(dev);
1411 #else
1412         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
1413                osd_dt_dev(d)->od_svname, (long)dev, rc);
1414 #endif
1415         RETURN(rc);
1416 }
1417
1418 /*
1419  * Concurrency: serialization provided by callers.
1420  */
1421 static int osd_init_capa_ctxt(const struct lu_env *env, struct dt_device *d,
1422                               int mode, unsigned long timeout, __u32 alg,
1423                               struct lustre_capa_key *keys)
1424 {
1425         struct osd_device *dev = osd_dt_dev(d);
1426         ENTRY;
1427
1428         dev->od_fl_capa = mode;
1429         dev->od_capa_timeout = timeout;
1430         dev->od_capa_alg = alg;
1431         dev->od_capa_keys = keys;
1432         RETURN(0);
1433 }
1434
1435 /**
1436  * Note: we do not count into QUOTA here.
1437  * If we mount with --data_journal we may need more.
1438  */
1439 const int osd_dto_credits_noquota[DTO_NR] = {
1440         /**
1441          * Insert.
1442          * INDEX_EXTRA_TRANS_BLOCKS(8) +
1443          * SINGLEDATA_TRANS_BLOCKS(8)
1444          * XXX Note: maybe iam need more, since iam have more level than
1445          *           EXT3 htree.
1446          */
1447         [DTO_INDEX_INSERT]  = 16,
1448         /**
1449          * Delete
1450          * just modify a single entry, probably merge few within a block
1451          */
1452         [DTO_INDEX_DELETE]  = 1,
1453         /**
1454          * Used for OI scrub
1455          */
1456         [DTO_INDEX_UPDATE]  = 16,
1457         /**
1458          * 4(inode, inode bits, groups, GDT)
1459          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
1460          */
1461         [DTO_OBJECT_CREATE] = 4,
1462         /**
1463          * 4(inode, inode bits, groups, GDT)
1464          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
1465          */
1466         [DTO_OBJECT_DELETE] = 4,
1467         /**
1468          * Attr set credits (inode)
1469          */
1470         [DTO_ATTR_SET_BASE] = 1,
1471         /**
1472          * Xattr set. The same as xattr of EXT3.
1473          * DATA_TRANS_BLOCKS(14)
1474          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
1475          * are also counted in. Do not know why?
1476          */
1477         [DTO_XATTR_SET]     = 14,
1478         /**
1479          * credits for inode change during write.
1480          */
1481         [DTO_WRITE_BASE]    = 3,
1482         /**
1483          * credits for single block write.
1484          */
1485         [DTO_WRITE_BLOCK]   = 14,
1486         /**
1487          * Attr set credits for chown.
1488          * This is extra credits for setattr, and it is null without quota
1489          */
1490         [DTO_ATTR_SET_CHOWN] = 0
1491 };
1492
1493 static const struct dt_device_operations osd_dt_ops = {
1494         .dt_root_get       = osd_root_get,
1495         .dt_statfs         = osd_statfs,
1496         .dt_trans_create   = osd_trans_create,
1497         .dt_trans_start    = osd_trans_start,
1498         .dt_trans_stop     = osd_trans_stop,
1499         .dt_trans_cb_add   = osd_trans_cb_add,
1500         .dt_conf_get       = osd_conf_get,
1501         .dt_sync           = osd_sync,
1502         .dt_ro             = osd_ro,
1503         .dt_commit_async   = osd_commit_async,
1504         .dt_init_capa_ctxt = osd_init_capa_ctxt,
1505 };
1506
1507 static void osd_object_read_lock(const struct lu_env *env,
1508                                  struct dt_object *dt, unsigned role)
1509 {
1510         struct osd_object *obj = osd_dt_obj(dt);
1511         struct osd_thread_info *oti = osd_oti_get(env);
1512
1513         LINVRNT(osd_invariant(obj));
1514
1515         LASSERT(obj->oo_owner != env);
1516         down_read_nested(&obj->oo_sem, role);
1517
1518         LASSERT(obj->oo_owner == NULL);
1519         oti->oti_r_locks++;
1520 }
1521
1522 static void osd_object_write_lock(const struct lu_env *env,
1523                                   struct dt_object *dt, unsigned role)
1524 {
1525         struct osd_object *obj = osd_dt_obj(dt);
1526         struct osd_thread_info *oti = osd_oti_get(env);
1527
1528         LINVRNT(osd_invariant(obj));
1529
1530         LASSERT(obj->oo_owner != env);
1531         down_write_nested(&obj->oo_sem, role);
1532
1533         LASSERT(obj->oo_owner == NULL);
1534         obj->oo_owner = env;
1535         oti->oti_w_locks++;
1536 }
1537
1538 static void osd_object_read_unlock(const struct lu_env *env,
1539                                    struct dt_object *dt)
1540 {
1541         struct osd_object *obj = osd_dt_obj(dt);
1542         struct osd_thread_info *oti = osd_oti_get(env);
1543
1544         LINVRNT(osd_invariant(obj));
1545
1546         LASSERT(oti->oti_r_locks > 0);
1547         oti->oti_r_locks--;
1548         up_read(&obj->oo_sem);
1549 }
1550
1551 static void osd_object_write_unlock(const struct lu_env *env,
1552                                     struct dt_object *dt)
1553 {
1554         struct osd_object *obj = osd_dt_obj(dt);
1555         struct osd_thread_info *oti = osd_oti_get(env);
1556
1557         LINVRNT(osd_invariant(obj));
1558
1559         LASSERT(obj->oo_owner == env);
1560         LASSERT(oti->oti_w_locks > 0);
1561         oti->oti_w_locks--;
1562         obj->oo_owner = NULL;
1563         up_write(&obj->oo_sem);
1564 }
1565
1566 static int osd_object_write_locked(const struct lu_env *env,
1567                                    struct dt_object *dt)
1568 {
1569         struct osd_object *obj = osd_dt_obj(dt);
1570
1571         LINVRNT(osd_invariant(obj));
1572
1573         return obj->oo_owner == env;
1574 }
1575
1576 static int capa_is_sane(const struct lu_env *env,
1577                         struct osd_device *dev,
1578                         struct lustre_capa *capa,
1579                         struct lustre_capa_key *keys)
1580 {
1581         struct osd_thread_info *oti = osd_oti_get(env);
1582         struct lustre_capa *tcapa = &oti->oti_capa;
1583         struct obd_capa *oc;
1584         int i, rc = 0;
1585         ENTRY;
1586
1587         oc = capa_lookup(dev->od_capa_hash, capa, 0);
1588         if (oc) {
1589                 if (capa_is_expired(oc)) {
1590                         DEBUG_CAPA(D_ERROR, capa, "expired");
1591                         rc = -ESTALE;
1592                 }
1593                 capa_put(oc);
1594                 RETURN(rc);
1595         }
1596
1597         if (capa_is_expired_sec(capa)) {
1598                 DEBUG_CAPA(D_ERROR, capa, "expired");
1599                 RETURN(-ESTALE);
1600         }
1601
1602         spin_lock(&capa_lock);
1603         for (i = 0; i < 2; i++) {
1604                 if (keys[i].lk_keyid == capa->lc_keyid) {
1605                         oti->oti_capa_key = keys[i];
1606                         break;
1607                 }
1608         }
1609         spin_unlock(&capa_lock);
1610
1611         if (i == 2) {
1612                 DEBUG_CAPA(D_ERROR, capa, "no matched capa key");
1613                 RETURN(-ESTALE);
1614         }
1615
1616         rc = capa_hmac(tcapa->lc_hmac, capa, oti->oti_capa_key.lk_key);
1617         if (rc)
1618                 RETURN(rc);
1619
1620         if (memcmp(tcapa->lc_hmac, capa->lc_hmac, sizeof(capa->lc_hmac))) {
1621                 DEBUG_CAPA(D_ERROR, capa, "HMAC mismatch");
1622                 RETURN(-EACCES);
1623         }
1624
1625         oc = capa_add(dev->od_capa_hash, capa);
1626         capa_put(oc);
1627
1628         RETURN(0);
1629 }
1630
1631 int osd_object_auth(const struct lu_env *env, struct dt_object *dt,
1632                     struct lustre_capa *capa, __u64 opc)
1633 {
1634         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
1635         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
1636         struct lu_capainfo *lci;
1637         int rc;
1638
1639         if (!osd->od_fl_capa)
1640                 return 0;
1641
1642         if (capa == BYPASS_CAPA)
1643                 return 0;
1644
1645         lci = lu_capainfo_get(env);
1646         if (unlikely(lci == NULL))
1647                 return 0;
1648
1649         if (lci->lci_auth == LC_ID_NONE)
1650                 return 0;
1651
1652         if (capa == NULL) {
1653                 CERROR("%s: no capability provided for FID "DFID": rc = %d\n",
1654                        osd_name(osd), PFID(fid), -EACCES);
1655                 return -EACCES;
1656         }
1657
1658         if (!lu_fid_eq(fid, &capa->lc_fid)) {
1659                 DEBUG_CAPA(D_ERROR, capa, "fid "DFID" mismatch with",
1660                            PFID(fid));
1661                 return -EACCES;
1662         }
1663
1664         if (!capa_opc_supported(capa, opc)) {
1665                 DEBUG_CAPA(D_ERROR, capa, "opc "LPX64" not supported by", opc);
1666                 return -EACCES;
1667         }
1668
1669         rc = capa_is_sane(env, osd, capa, osd->od_capa_keys);
1670         if (rc != 0) {
1671                 DEBUG_CAPA(D_ERROR, capa, "insane: rc = %d", rc);
1672                 return -EACCES;
1673         }
1674
1675         return 0;
1676 }
1677
1678 static struct timespec *osd_inode_time(const struct lu_env *env,
1679                                        struct inode *inode, __u64 seconds)
1680 {
1681         struct osd_thread_info  *oti = osd_oti_get(env);
1682         struct timespec         *t   = &oti->oti_time;
1683
1684         t->tv_sec = seconds;
1685         t->tv_nsec = 0;
1686         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
1687         return t;
1688 }
1689
1690
1691 static void osd_inode_getattr(const struct lu_env *env,
1692                               struct inode *inode, struct lu_attr *attr)
1693 {
1694         attr->la_valid      |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
1695                                LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
1696                                LA_FLAGS | LA_NLINK | LA_RDEV | LA_BLKSIZE |
1697                                LA_TYPE;
1698
1699         attr->la_atime      = LTIME_S(inode->i_atime);
1700         attr->la_mtime      = LTIME_S(inode->i_mtime);
1701         attr->la_ctime      = LTIME_S(inode->i_ctime);
1702         attr->la_mode       = inode->i_mode;
1703         attr->la_size       = i_size_read(inode);
1704         attr->la_blocks     = inode->i_blocks;
1705         attr->la_uid        = inode->i_uid;
1706         attr->la_gid        = inode->i_gid;
1707         attr->la_flags      = LDISKFS_I(inode)->i_flags;
1708         attr->la_nlink      = inode->i_nlink;
1709         attr->la_rdev       = inode->i_rdev;
1710         attr->la_blksize    = 1 << inode->i_blkbits;
1711         attr->la_blkbits    = inode->i_blkbits;
1712 }
1713
1714 static int osd_attr_get(const struct lu_env *env,
1715                         struct dt_object *dt,
1716                         struct lu_attr *attr,
1717                         struct lustre_capa *capa)
1718 {
1719         struct osd_object *obj = osd_dt_obj(dt);
1720
1721         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1722         LINVRNT(osd_invariant(obj));
1723
1724         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
1725                 return -EACCES;
1726
1727         spin_lock(&obj->oo_guard);
1728         osd_inode_getattr(env, obj->oo_inode, attr);
1729         spin_unlock(&obj->oo_guard);
1730         return 0;
1731 }
1732
1733 static int osd_declare_attr_set(const struct lu_env *env,
1734                                 struct dt_object *dt,
1735                                 const struct lu_attr *attr,
1736                                 struct thandle *handle)
1737 {
1738         struct osd_thandle     *oh;
1739         struct osd_object      *obj;
1740         struct osd_thread_info *info = osd_oti_get(env);
1741         struct lquota_id_info  *qi = &info->oti_qi;
1742         long long               bspace;
1743         int                     rc = 0;
1744         bool                    allocated;
1745         ENTRY;
1746
1747         LASSERT(dt != NULL);
1748         LASSERT(handle != NULL);
1749
1750         obj = osd_dt_obj(dt);
1751         LASSERT(osd_invariant(obj));
1752
1753         oh = container_of0(handle, struct osd_thandle, ot_super);
1754         LASSERT(oh->ot_handle == NULL);
1755
1756         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
1757                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
1758
1759         if (attr == NULL || obj->oo_inode == NULL)
1760                 RETURN(rc);
1761
1762         bspace   = obj->oo_inode->i_blocks;
1763         bspace <<= obj->oo_inode->i_sb->s_blocksize_bits;
1764         bspace   = toqb(bspace);
1765
1766         /* Changing ownership is always preformed by super user, it should not
1767          * fail with EDQUOT.
1768          *
1769          * We still need to call the osd_declare_qid() to calculate the journal
1770          * credits for updating quota accounting files and to trigger quota
1771          * space adjustment once the operation is completed.*/
1772         if ((attr->la_valid & LA_UID) != 0 &&
1773              attr->la_uid != obj->oo_inode->i_uid) {
1774                 qi->lqi_type = USRQUOTA;
1775
1776                 /* inode accounting */
1777                 qi->lqi_is_blk = false;
1778
1779                 /* one more inode for the new owner ... */
1780                 qi->lqi_id.qid_uid = attr->la_uid;
1781                 qi->lqi_space      = 1;
1782                 allocated = (attr->la_uid == 0) ? true : false;
1783                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1784                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1785                         rc = 0;
1786                 if (rc)
1787                         RETURN(rc);
1788
1789                 /* and one less inode for the current uid */
1790                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1791                 qi->lqi_space      = -1;
1792                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1793                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1794                         rc = 0;
1795                 if (rc)
1796                         RETURN(rc);
1797
1798                 /* block accounting */
1799                 qi->lqi_is_blk = true;
1800
1801                 /* more blocks for the new owner ... */
1802                 qi->lqi_id.qid_uid = attr->la_uid;
1803                 qi->lqi_space      = bspace;
1804                 allocated = (attr->la_uid == 0) ? true : false;
1805                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1806                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1807                         rc = 0;
1808                 if (rc)
1809                         RETURN(rc);
1810
1811                 /* and finally less blocks for the current owner */
1812                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1813                 qi->lqi_space      = -bspace;
1814                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1815                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1816                         rc = 0;
1817                 if (rc)
1818                         RETURN(rc);
1819         }
1820
1821         if (attr->la_valid & LA_GID &&
1822             attr->la_gid != obj->oo_inode->i_gid) {
1823                 qi->lqi_type = GRPQUOTA;
1824
1825                 /* inode accounting */
1826                 qi->lqi_is_blk = false;
1827
1828                 /* one more inode for the new group owner ... */
1829                 qi->lqi_id.qid_gid = attr->la_gid;
1830                 qi->lqi_space      = 1;
1831                 allocated = (attr->la_gid == 0) ? true : false;
1832                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1833                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1834                         rc = 0;
1835                 if (rc)
1836                         RETURN(rc);
1837
1838                 /* and one less inode for the current gid */
1839                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1840                 qi->lqi_space      = -1;
1841                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1842                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1843                         rc = 0;
1844                 if (rc)
1845                         RETURN(rc);
1846
1847                 /* block accounting */
1848                 qi->lqi_is_blk = true;
1849
1850                 /* more blocks for the new owner ... */
1851                 qi->lqi_id.qid_gid = attr->la_gid;
1852                 qi->lqi_space      = bspace;
1853                 allocated = (attr->la_gid == 0) ? true : false;
1854                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1855                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1856                         rc = 0;
1857                 if (rc)
1858                         RETURN(rc);
1859
1860                 /* and finally less blocks for the current owner */
1861                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1862                 qi->lqi_space      = -bspace;
1863                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1864                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1865                         rc = 0;
1866                 if (rc)
1867                         RETURN(rc);
1868         }
1869
1870         RETURN(rc);
1871 }
1872
1873 static int osd_inode_setattr(const struct lu_env *env,
1874                              struct inode *inode, const struct lu_attr *attr)
1875 {
1876         __u64 bits;
1877
1878         bits = attr->la_valid;
1879
1880         if (bits & LA_ATIME)
1881                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
1882         if (bits & LA_CTIME)
1883                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
1884         if (bits & LA_MTIME)
1885                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
1886         if (bits & LA_SIZE) {
1887                 LDISKFS_I(inode)->i_disksize = attr->la_size;
1888                 i_size_write(inode, attr->la_size);
1889         }
1890
1891 #if 0
1892         /* OSD should not change "i_blocks" which is used by quota.
1893          * "i_blocks" should be changed by ldiskfs only. */
1894         if (bits & LA_BLOCKS)
1895                 inode->i_blocks = attr->la_blocks;
1896 #endif
1897         if (bits & LA_MODE)
1898                 inode->i_mode   = (inode->i_mode & S_IFMT) |
1899                         (attr->la_mode & ~S_IFMT);
1900         if (bits & LA_UID)
1901                 inode->i_uid    = attr->la_uid;
1902         if (bits & LA_GID)
1903                 inode->i_gid    = attr->la_gid;
1904         if (bits & LA_NLINK)
1905                 set_nlink(inode, attr->la_nlink);
1906         if (bits & LA_RDEV)
1907                 inode->i_rdev   = attr->la_rdev;
1908
1909         if (bits & LA_FLAGS) {
1910                 /* always keep S_NOCMTIME */
1911                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
1912                                  S_NOCMTIME;
1913         }
1914         return 0;
1915 }
1916
1917 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
1918 {
1919         if ((attr->la_valid & LA_UID && attr->la_uid != inode->i_uid) ||
1920             (attr->la_valid & LA_GID && attr->la_gid != inode->i_gid)) {
1921                 struct iattr    iattr;
1922                 int             rc;
1923
1924                 iattr.ia_valid = 0;
1925                 if (attr->la_valid & LA_UID)
1926                         iattr.ia_valid |= ATTR_UID;
1927                 if (attr->la_valid & LA_GID)
1928                         iattr.ia_valid |= ATTR_GID;
1929                 iattr.ia_uid = attr->la_uid;
1930                 iattr.ia_gid = attr->la_gid;
1931
1932                 rc = ll_vfs_dq_transfer(inode, &iattr);
1933                 if (rc) {
1934                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
1935                                "enforcement enabled on the ldiskfs filesystem?",
1936                                inode->i_sb->s_id, rc);
1937                         return rc;
1938                 }
1939         }
1940         return 0;
1941 }
1942
1943 static int osd_attr_set(const struct lu_env *env,
1944                         struct dt_object *dt,
1945                         const struct lu_attr *attr,
1946                         struct thandle *handle,
1947                         struct lustre_capa *capa)
1948 {
1949         struct osd_object *obj = osd_dt_obj(dt);
1950         struct inode      *inode;
1951         int rc;
1952
1953         LASSERT(handle != NULL);
1954         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1955         LASSERT(osd_invariant(obj));
1956
1957         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
1958                 return -EACCES;
1959
1960         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
1961
1962         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING)) {
1963                 struct osd_thread_info  *oti  = osd_oti_get(env);
1964                 const struct lu_fid     *fid0 = lu_object_fid(&dt->do_lu);
1965                 struct lu_fid           *fid1 = &oti->oti_fid;
1966                 struct osd_inode_id     *id   = &oti->oti_id;
1967                 struct iam_path_descr   *ipd;
1968                 struct iam_container    *bag;
1969                 struct osd_thandle      *oh;
1970                 int                      rc;
1971
1972                 fid_cpu_to_be(fid1, fid0);
1973                 memset(id, 1, sizeof(*id));
1974                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
1975                                   fid0)->oi_dir.od_container;
1976                 ipd = osd_idx_ipd_get(env, bag);
1977                 if (unlikely(ipd == NULL))
1978                         RETURN(-ENOMEM);
1979
1980                 oh = container_of0(handle, struct osd_thandle, ot_super);
1981                 rc = iam_update(oh->ot_handle, bag, (const struct iam_key *)fid1,
1982                                 (const struct iam_rec *)id, ipd);
1983                 osd_ipd_put(env, bag, ipd);
1984                 return(rc > 0 ? 0 : rc);
1985         }
1986
1987         inode = obj->oo_inode;
1988         ll_vfs_dq_init(inode);
1989
1990         rc = osd_quota_transfer(inode, attr);
1991         if (rc)
1992                 return rc;
1993
1994         spin_lock(&obj->oo_guard);
1995         rc = osd_inode_setattr(env, inode, attr);
1996         spin_unlock(&obj->oo_guard);
1997
1998         if (!rc)
1999                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2000         return rc;
2001 }
2002
2003 struct dentry *osd_child_dentry_get(const struct lu_env *env,
2004                                     struct osd_object *obj,
2005                                     const char *name, const int namelen)
2006 {
2007         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
2008 }
2009
2010 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
2011                       umode_t mode, struct dt_allocation_hint *hint,
2012                       struct thandle *th)
2013 {
2014         int result;
2015         struct osd_device  *osd = osd_obj2dev(obj);
2016         struct osd_thandle *oth;
2017         struct dt_object   *parent = NULL;
2018         struct inode       *inode;
2019
2020         LINVRNT(osd_invariant(obj));
2021         LASSERT(obj->oo_inode == NULL);
2022         LASSERT(obj->oo_hl_head == NULL);
2023
2024         if (S_ISDIR(mode) && ldiskfs_pdo) {
2025                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
2026                 if (obj->oo_hl_head == NULL)
2027                         return -ENOMEM;
2028         }
2029
2030         oth = container_of(th, struct osd_thandle, ot_super);
2031         LASSERT(oth->ot_handle->h_transaction != NULL);
2032
2033         if (hint && hint->dah_parent)
2034                 parent = hint->dah_parent;
2035
2036         inode = ldiskfs_create_inode(oth->ot_handle,
2037                                      parent ? osd_dt_obj(parent)->oo_inode :
2038                                               osd_sb(osd)->s_root->d_inode,
2039                                      mode);
2040         if (!IS_ERR(inode)) {
2041                 /* Do not update file c/mtime in ldiskfs.
2042                  * NB: don't need any lock because no contention at this
2043                  * early stage */
2044                 inode->i_flags |= S_NOCMTIME;
2045
2046                 /* For new created object, it must be consistent,
2047                  * and it is unnecessary to scrub against it. */
2048                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
2049                 obj->oo_inode = inode;
2050                 result = 0;
2051         } else {
2052                 if (obj->oo_hl_head != NULL) {
2053                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
2054                         obj->oo_hl_head = NULL;
2055                 }
2056                 result = PTR_ERR(inode);
2057         }
2058         LINVRNT(osd_invariant(obj));
2059         return result;
2060 }
2061
2062 enum {
2063         OSD_NAME_LEN = 255
2064 };
2065
2066 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
2067                      struct lu_attr *attr,
2068                      struct dt_allocation_hint *hint,
2069                      struct dt_object_format *dof,
2070                      struct thandle *th)
2071 {
2072         int result;
2073         struct osd_thandle *oth;
2074         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX));
2075
2076         LASSERT(S_ISDIR(attr->la_mode));
2077
2078         oth = container_of(th, struct osd_thandle, ot_super);
2079         LASSERT(oth->ot_handle->h_transaction != NULL);
2080         result = osd_mkfile(info, obj, mode, hint, th);
2081
2082         return result;
2083 }
2084
2085 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
2086                         struct lu_attr *attr,
2087                         struct dt_allocation_hint *hint,
2088                         struct dt_object_format *dof,
2089                         struct thandle *th)
2090 {
2091         int result;
2092         struct osd_thandle *oth;
2093         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
2094
2095         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
2096
2097         LASSERT(S_ISREG(attr->la_mode));
2098
2099         oth = container_of(th, struct osd_thandle, ot_super);
2100         LASSERT(oth->ot_handle->h_transaction != NULL);
2101
2102         result = osd_mkfile(info, obj, mode, hint, th);
2103         if (result == 0) {
2104                 LASSERT(obj->oo_inode != NULL);
2105                 if (feat->dif_flags & DT_IND_VARKEY)
2106                         result = iam_lvar_create(obj->oo_inode,
2107                                                  feat->dif_keysize_max,
2108                                                  feat->dif_ptrsize,
2109                                                  feat->dif_recsize_max,
2110                                                  oth->ot_handle);
2111                 else
2112                         result = iam_lfix_create(obj->oo_inode,
2113                                                  feat->dif_keysize_max,
2114                                                  feat->dif_ptrsize,
2115                                                  feat->dif_recsize_max,
2116                                                  oth->ot_handle);
2117
2118         }
2119         return result;
2120 }
2121
2122 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
2123                      struct lu_attr *attr,
2124                      struct dt_allocation_hint *hint,
2125                      struct dt_object_format *dof,
2126                      struct thandle *th)
2127 {
2128         LASSERT(S_ISREG(attr->la_mode));
2129         return osd_mkfile(info, obj, (attr->la_mode &
2130                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2131 }
2132
2133 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
2134                      struct lu_attr *attr,
2135                      struct dt_allocation_hint *hint,
2136                      struct dt_object_format *dof,
2137                      struct thandle *th)
2138 {
2139         LASSERT(S_ISLNK(attr->la_mode));
2140         return osd_mkfile(info, obj, (attr->la_mode &
2141                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2142 }
2143
2144 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
2145                      struct lu_attr *attr,
2146                      struct dt_allocation_hint *hint,
2147                      struct dt_object_format *dof,
2148                      struct thandle *th)
2149 {
2150         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
2151         int result;
2152
2153         LINVRNT(osd_invariant(obj));
2154         LASSERT(obj->oo_inode == NULL);
2155         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
2156                 S_ISFIFO(mode) || S_ISSOCK(mode));
2157
2158         result = osd_mkfile(info, obj, mode, hint, th);
2159         if (result == 0) {
2160                 LASSERT(obj->oo_inode != NULL);
2161                 /*
2162                  * This inode should be marked dirty for i_rdev.  Currently
2163                  * that is done in the osd_attr_init().
2164                  */
2165                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
2166                                    attr->la_rdev);
2167         }
2168         LINVRNT(osd_invariant(obj));
2169         return result;
2170 }
2171
2172 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
2173                               struct lu_attr *,
2174                               struct dt_allocation_hint *hint,
2175                               struct dt_object_format *dof,
2176                               struct thandle *);
2177
2178 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
2179 {
2180         osd_obj_type_f result;
2181
2182         switch (type) {
2183         case DFT_DIR:
2184                 result = osd_mkdir;
2185                 break;
2186         case DFT_REGULAR:
2187                 result = osd_mkreg;
2188                 break;
2189         case DFT_SYM:
2190                 result = osd_mksym;
2191                 break;
2192         case DFT_NODE:
2193                 result = osd_mknod;
2194                 break;
2195         case DFT_INDEX:
2196                 result = osd_mk_index;
2197                 break;
2198
2199         default:
2200                 LBUG();
2201                 break;
2202         }
2203         return result;
2204 }
2205
2206
2207 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
2208                         struct dt_object *parent, struct dt_object *child,
2209                         umode_t child_mode)
2210 {
2211         LASSERT(ah);
2212
2213         ah->dah_parent = parent;
2214         ah->dah_mode = child_mode;
2215 }
2216
2217 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
2218                           struct lu_attr *attr, struct dt_object_format *dof)
2219 {
2220         struct inode   *inode = obj->oo_inode;
2221         __u64           valid = attr->la_valid;
2222         int             result;
2223
2224         attr->la_valid &= ~(LA_TYPE | LA_MODE);
2225
2226         if (dof->dof_type != DFT_NODE)
2227                 attr->la_valid &= ~LA_RDEV;
2228         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
2229                 attr->la_valid &= ~LA_ATIME;
2230         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
2231                 attr->la_valid &= ~LA_CTIME;
2232         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
2233                 attr->la_valid &= ~LA_MTIME;
2234
2235         result = osd_quota_transfer(inode, attr);
2236         if (result)
2237                 return;
2238
2239         if (attr->la_valid != 0) {
2240                 result = osd_inode_setattr(info->oti_env, inode, attr);
2241                 /*
2242                  * The osd_inode_setattr() should always succeed here.  The
2243                  * only error that could be returned is EDQUOT when we are
2244                  * trying to change the UID or GID of the inode. However, this
2245                  * should not happen since quota enforcement is no longer
2246                  * enabled on ldiskfs (lquota takes care of it).
2247                  */
2248                 LASSERTF(result == 0, "%d", result);
2249                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2250         }
2251
2252         attr->la_valid = valid;
2253 }
2254
2255 /**
2256  * Helper function for osd_object_create()
2257  *
2258  * \retval 0, on success
2259  */
2260 static int __osd_object_create(struct osd_thread_info *info,
2261                                struct osd_object *obj, struct lu_attr *attr,
2262                                struct dt_allocation_hint *hint,
2263                                struct dt_object_format *dof,
2264                                struct thandle *th)
2265 {
2266         int     result;
2267         __u32   umask;
2268
2269         /* we drop umask so that permissions we pass are not affected */
2270         umask = current->fs->umask;
2271         current->fs->umask = 0;
2272
2273         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
2274                                                   th);
2275         if (result == 0) {
2276                 osd_attr_init(info, obj, attr, dof);
2277                 osd_object_init0(obj);
2278                 /* bz 24037 */
2279                 if (obj->oo_inode && (obj->oo_inode->i_state & I_NEW))
2280                         unlock_new_inode(obj->oo_inode);
2281         }
2282
2283         /* restore previous umask value */
2284         current->fs->umask = umask;
2285
2286         return result;
2287 }
2288
2289 /**
2290  * Helper function for osd_object_create()
2291  *
2292  * \retval 0, on success
2293  */
2294 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
2295                            const struct lu_fid *fid, struct thandle *th)
2296 {
2297         struct osd_thread_info *info = osd_oti_get(env);
2298         struct osd_inode_id    *id   = &info->oti_id;
2299         struct osd_device      *osd  = osd_obj2dev(obj);
2300         struct osd_thandle     *oh;
2301
2302         LASSERT(obj->oo_inode != NULL);
2303
2304         oh = container_of0(th, struct osd_thandle, ot_super);
2305         LASSERT(oh->ot_handle);
2306
2307         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
2308         return osd_oi_insert(info, osd, fid, id, oh->ot_handle, OI_CHECK_FLD);
2309 }
2310
2311 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
2312                    obd_seq seq, struct lu_seq_range *range)
2313 {
2314         struct seq_server_site  *ss = osd_seq_site(osd);
2315
2316         if (fid_seq_is_idif(seq)) {
2317                 fld_range_set_ost(range);
2318                 range->lsr_index = idif_ost_idx(seq);
2319                 return 0;
2320         }
2321
2322         if (!fid_seq_in_fldb(seq)) {
2323                 fld_range_set_mdt(range);
2324                 if (ss != NULL)
2325                         /* FIXME: If ss is NULL, it suppose not get lsr_index
2326                          * at all */
2327                         range->lsr_index = ss->ss_node_id;
2328                 return 0;
2329         }
2330
2331         LASSERT(ss != NULL);
2332         fld_range_set_any(range);
2333         /* OSD will only do local fld lookup */
2334         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
2335 }
2336
2337 /*
2338  * Concurrency: no external locking is necessary.
2339  */
2340 static int osd_declare_object_create(const struct lu_env *env,
2341                                      struct dt_object *dt,
2342                                      struct lu_attr *attr,
2343                                      struct dt_allocation_hint *hint,
2344                                      struct dt_object_format *dof,
2345                                      struct thandle *handle)
2346 {
2347         struct osd_thandle      *oh;
2348         int                      rc;
2349         ENTRY;
2350
2351         LASSERT(handle != NULL);
2352
2353         oh = container_of0(handle, struct osd_thandle, ot_super);
2354         LASSERT(oh->ot_handle == NULL);
2355
2356         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
2357                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
2358         /* Reuse idle OI block may cause additional one OI block
2359          * to be changed. */
2360         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2361                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
2362
2363         /* If this is directory, then we expect . and .. to be inserted as
2364          * well. The one directory block always needs to be created for the
2365          * directory, so we could use DTO_WRITE_BASE here (GDT, block bitmap,
2366          * block), there is no danger of needing a tree for the first block.
2367          */
2368         if (attr && S_ISDIR(attr->la_mode)) {
2369                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2370                                      osd_dto_credits_noquota[DTO_WRITE_BASE]);
2371                 osd_trans_declare_op(env, oh, OSD_OT_INSERT, 0);
2372         }
2373
2374         if (!attr)
2375                 RETURN(0);
2376
2377         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid, 1, oh,
2378                                    false, false, NULL, false);
2379         if (rc != 0)
2380                 RETURN(rc);
2381
2382         RETURN(rc);
2383 }
2384
2385 static int osd_object_create(const struct lu_env *env, struct dt_object *dt,
2386                              struct lu_attr *attr,
2387                              struct dt_allocation_hint *hint,
2388                              struct dt_object_format *dof,
2389                              struct thandle *th)
2390 {
2391         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2392         struct osd_object      *obj    = osd_dt_obj(dt);
2393         struct osd_thread_info *info   = osd_oti_get(env);
2394         int result;
2395
2396         ENTRY;
2397
2398         LINVRNT(osd_invariant(obj));
2399         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2400         LASSERT(osd_write_locked(env, obj));
2401         LASSERT(th != NULL);
2402
2403         if (unlikely(fid_is_acct(fid)))
2404                 /* Quota files can't be created from the kernel any more,
2405                  * 'tune2fs -O quota' will take care of creating them */
2406                 RETURN(-EPERM);
2407
2408         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2409         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2410
2411         result = __osd_object_create(info, obj, attr, hint, dof, th);
2412         if (result == 0)
2413                 result = __osd_oi_insert(env, obj, fid, th);
2414
2415         LASSERT(ergo(result == 0,
2416                      dt_object_exists(dt) && !dt_object_remote(dt)));
2417
2418         LASSERT(osd_invariant(obj));
2419         RETURN(result);
2420 }
2421
2422 /**
2423  * Called to destroy on-disk representation of the object
2424  *
2425  * Concurrency: must be locked
2426  */
2427 static int osd_declare_object_destroy(const struct lu_env *env,
2428                                       struct dt_object *dt,
2429                                       struct thandle *th)
2430 {
2431         struct osd_object  *obj = osd_dt_obj(dt);
2432         struct inode       *inode = obj->oo_inode;
2433         struct osd_thandle *oh;
2434         int                 rc;
2435         ENTRY;
2436
2437         oh = container_of0(th, struct osd_thandle, ot_super);
2438         LASSERT(oh->ot_handle == NULL);
2439         LASSERT(inode);
2440
2441         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
2442                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
2443         /* Recycle idle OI leaf may cause additional three OI blocks
2444          * to be changed. */
2445         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
2446                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
2447         /* one less inode */
2448         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, -1, oh,
2449                                    false, true, NULL, false);
2450         if (rc)
2451                 RETURN(rc);
2452         /* data to be truncated */
2453         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
2454                                    true, true, NULL, false);
2455         RETURN(rc);
2456 }
2457
2458 static int osd_object_destroy(const struct lu_env *env,
2459                               struct dt_object *dt,
2460                               struct thandle *th)
2461 {
2462         const struct lu_fid    *fid = lu_object_fid(&dt->do_lu);
2463         struct osd_object      *obj = osd_dt_obj(dt);
2464         struct inode           *inode = obj->oo_inode;
2465         struct osd_device      *osd = osd_obj2dev(obj);
2466         struct osd_thandle     *oh;
2467         int                     result;
2468         ENTRY;
2469
2470         oh = container_of0(th, struct osd_thandle, ot_super);
2471         LASSERT(oh->ot_handle);
2472         LASSERT(inode);
2473         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
2474
2475         if (unlikely(fid_is_acct(fid)))
2476                 RETURN(-EPERM);
2477
2478         if (S_ISDIR(inode->i_mode)) {
2479                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1 ||
2480                         inode->i_nlink == 2);
2481                 /* it will check/delete the inode from remote parent,
2482                  * how to optimize it? unlink performance impaction XXX */
2483                 result = osd_delete_from_remote_parent(env, osd, obj, oh);
2484                 if (result != 0 && result != -ENOENT) {
2485                         CERROR("%s: delete inode "DFID": rc = %d\n",
2486                                osd_name(osd), PFID(fid), result);
2487                 }
2488                 spin_lock(&obj->oo_guard);
2489                 clear_nlink(inode);
2490                 spin_unlock(&obj->oo_guard);
2491                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2492         }
2493
2494         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
2495
2496         result = osd_oi_delete(osd_oti_get(env), osd, fid, oh->ot_handle,
2497                                OI_CHECK_FLD);
2498
2499         /* XXX: add to ext3 orphan list */
2500         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
2501
2502         /* not needed in the cache anymore */
2503         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
2504
2505         RETURN(0);
2506 }
2507
2508 /**
2509  * Put the fid into lustre_mdt_attrs, and then place the structure
2510  * inode's ea. This fid should not be altered during the life time
2511  * of the inode.
2512  *
2513  * \retval +ve, on success
2514  * \retval -ve, on error
2515  *
2516  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
2517  */
2518 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
2519                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
2520 {
2521         struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
2522         int                      rc;
2523         ENTRY;
2524
2525         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
2526                 RETURN(0);
2527
2528         lustre_lma_init(lma, fid, compat, incompat);
2529         lustre_lma_swab(lma);
2530
2531         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma, sizeof(*lma),
2532                              XATTR_CREATE);
2533         /* LMA may already exist, but we need to check that all the
2534          * desired compat/incompat flags have been added. */
2535         if (unlikely(rc == -EEXIST)) {
2536                 if (compat == 0 && incompat == 0)
2537                         RETURN(0);
2538
2539                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
2540                                      XATTR_NAME_LMA, info->oti_mdt_attrs_old,
2541                                      LMA_OLD_SIZE);
2542                 if (rc <= 0)
2543                         RETURN(-EINVAL);
2544
2545                 lustre_lma_swab(lma);
2546                 if (!(~lma->lma_compat & compat) &&
2547                     !(~lma->lma_incompat & incompat))
2548                         RETURN(0);
2549
2550                 lma->lma_compat |= compat;
2551                 lma->lma_incompat |= incompat;
2552                 lustre_lma_swab(lma);
2553                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
2554                                      sizeof(*lma), XATTR_REPLACE);
2555         }
2556
2557         RETURN(rc);
2558 }
2559
2560 /**
2561  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
2562  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
2563  * To have compatilibility with 1.8 ldiskfs driver we need to have
2564  * magic number at start of fid data.
2565  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
2566  * its inmemory API.
2567  */
2568 void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
2569                                   const struct dt_rec *fid)
2570 {
2571         if (!fid_is_namespace_visible((const struct lu_fid *)fid) ||
2572             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
2573                 param->edp_magic = 0;
2574                 return;
2575         }
2576
2577         param->edp_magic = LDISKFS_LUFID_MAGIC;
2578         param->edp_len =  sizeof(struct lu_fid) + 1;
2579         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
2580 }
2581
2582 /**
2583  * Try to read the fid from inode ea into dt_rec.
2584  *
2585  * \param fid object fid.
2586  *
2587  * \retval 0 on success
2588  */
2589 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
2590                           __u32 ino, struct lu_fid *fid,
2591                           struct osd_inode_id *id)
2592 {
2593         struct osd_thread_info *info  = osd_oti_get(env);
2594         struct inode           *inode;
2595         ENTRY;
2596
2597         osd_id_gen(id, ino, OSD_OII_NOGEN);
2598         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
2599         if (IS_ERR(inode))
2600                 RETURN(PTR_ERR(inode));
2601
2602         iput(inode);
2603         RETURN(0);
2604 }
2605
2606 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
2607                                         struct inode *dir,
2608                                         struct inode  *parent_dir,
2609                                         const struct dt_rec *dot_fid,
2610                                         const struct dt_rec *dot_dot_fid,
2611                                         struct osd_thandle *oth)
2612 {
2613         struct ldiskfs_dentry_param *dot_ldp;
2614         struct ldiskfs_dentry_param *dot_dot_ldp;
2615
2616         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
2617         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
2618
2619         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
2620         dot_ldp->edp_magic = 0;
2621         return ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
2622                                         dir, dot_ldp, dot_dot_ldp);
2623 }
2624
2625 /**
2626  * Create an local agent inode for remote entry
2627  */
2628 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
2629                                                   struct osd_device *osd,
2630                                                   struct osd_object *pobj,
2631                                                   const struct lu_fid *fid,
2632                                                   struct thandle *th)
2633 {
2634         struct osd_thread_info  *info = osd_oti_get(env);
2635         struct inode            *local;
2636         struct osd_thandle      *oh;
2637         int                     rc;
2638         ENTRY;
2639
2640         LASSERT(th);
2641         oh = container_of(th, struct osd_thandle, ot_super);
2642         LASSERT(oh->ot_handle->h_transaction != NULL);
2643
2644         /* FIXME: Insert index api needs to know the mode of
2645          * the remote object. Just use S_IFDIR for now */
2646         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, S_IFDIR);
2647         if (IS_ERR(local)) {
2648                 CERROR("%s: create local error %d\n", osd_name(osd),
2649                        (int)PTR_ERR(local));
2650                 RETURN(local);
2651         }
2652
2653         /* Set special LMA flag for local agent inode */
2654         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
2655         if (rc != 0) {
2656                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
2657                        osd_name(osd), PFID(fid), rc);
2658                 RETURN(ERR_PTR(rc));
2659         }
2660
2661         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
2662                 (const struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
2663                 (const struct dt_rec *)fid, oh);
2664         if (rc != 0) {
2665                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
2666                         osd_name(osd), PFID(fid), rc);
2667                 RETURN(ERR_PTR(rc));
2668         }
2669
2670         RETURN(local);
2671 }
2672
2673 /**
2674  * Delete local agent inode for remote entry
2675  */
2676 static int osd_delete_local_agent_inode(const struct lu_env *env,
2677                                         struct osd_device *osd,
2678                                         const struct lu_fid *fid,
2679                                         __u32 ino, struct osd_thandle *oh)
2680 {
2681         struct osd_thread_info  *oti = osd_oti_get(env);
2682         struct osd_inode_id     *id = &oti->oti_id;
2683         struct inode            *inode;
2684         ENTRY;
2685
2686         id->oii_ino = le32_to_cpu(ino);
2687         id->oii_gen = OSD_OII_NOGEN;
2688         inode = osd_iget(oti, osd, id);
2689         if (IS_ERR(inode)) {
2690                 CERROR("%s: iget error "DFID" id %u:%u\n", osd_name(osd),
2691                        PFID(fid), id->oii_ino, id->oii_gen);
2692                 RETURN(PTR_ERR(inode));
2693         }
2694
2695         clear_nlink(inode);
2696         mark_inode_dirty(inode);
2697         CDEBUG(D_INODE, "%s: delete remote inode "DFID" %lu\n",
2698                 osd_name(osd), PFID(fid), inode->i_ino);
2699         iput(inode);
2700         RETURN(0);
2701 }
2702
2703 /**
2704  * OSD layer object create function for interoperability mode (b11826).
2705  * This is mostly similar to osd_object_create(). Only difference being, fid is
2706  * inserted into inode ea here.
2707  *
2708  * \retval   0, on success
2709  * \retval -ve, on error
2710  */
2711 static int osd_object_ea_create(const struct lu_env *env, struct dt_object *dt,
2712                                 struct lu_attr *attr,
2713                                 struct dt_allocation_hint *hint,
2714                                 struct dt_object_format *dof,
2715                                 struct thandle *th)
2716 {
2717         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2718         struct osd_object      *obj    = osd_dt_obj(dt);
2719         struct osd_thread_info *info   = osd_oti_get(env);
2720         int                     result;
2721
2722         ENTRY;
2723
2724         LASSERT(osd_invariant(obj));
2725         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2726         LASSERT(osd_write_locked(env, obj));
2727         LASSERT(th != NULL);
2728
2729         if (unlikely(fid_is_acct(fid)))
2730                 /* Quota files can't be created from the kernel any more,
2731                  * 'tune2fs -O quota' will take care of creating them */
2732                 RETURN(-EPERM);
2733
2734         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2735         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2736
2737         result = __osd_object_create(info, obj, attr, hint, dof, th);
2738         if (result == 0)
2739                 result = osd_ea_fid_set(info, obj->oo_inode, fid,
2740                                 fid_is_on_ost(info, osd_obj2dev(obj),
2741                                               fid, OI_CHECK_FLD) ?
2742                                 LMAC_FID_ON_OST : 0, 0);
2743
2744         if (result == 0)
2745                 result = __osd_oi_insert(env, obj, fid, th);
2746
2747         LASSERT(ergo(result == 0,
2748                      dt_object_exists(dt) && !dt_object_remote(dt)));
2749         LINVRNT(osd_invariant(obj));
2750         RETURN(result);
2751 }
2752
2753 static int osd_declare_object_ref_add(const struct lu_env *env,
2754                                       struct dt_object *dt,
2755                                       struct thandle *handle)
2756 {
2757         struct osd_thandle       *oh;
2758
2759         /* it's possible that object doesn't exist yet */
2760         LASSERT(handle != NULL);
2761
2762         oh = container_of0(handle, struct osd_thandle, ot_super);
2763         LASSERT(oh->ot_handle == NULL);
2764
2765         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
2766                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2767
2768         return 0;
2769 }
2770
2771 /*
2772  * Concurrency: @dt is write locked.
2773  */
2774 static int osd_object_ref_add(const struct lu_env *env,
2775                               struct dt_object *dt, struct thandle *th)
2776 {
2777         struct osd_object  *obj = osd_dt_obj(dt);
2778         struct inode       *inode = obj->oo_inode;
2779         struct osd_thandle *oh;
2780         int                 rc = 0;
2781
2782         LINVRNT(osd_invariant(obj));
2783         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2784         LASSERT(osd_write_locked(env, obj));
2785         LASSERT(th != NULL);
2786
2787         oh = container_of0(th, struct osd_thandle, ot_super);
2788         LASSERT(oh->ot_handle != NULL);
2789
2790         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
2791
2792         /*
2793          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
2794          * (65000) subdirectories by storing "1" in i_nlink if the link count
2795          * would otherwise overflow. Directory tranversal tools understand
2796          * that (st_nlink == 1) indicates that the filesystem dose not track
2797          * hard links count on the directory, and will not abort subdirectory
2798          * scanning early once (st_nlink - 2) subdirs have been found.
2799          *
2800          * This also has to properly handle the case of inodes with nlink == 0
2801          * in case they are being linked into the PENDING directory
2802          */
2803         spin_lock(&obj->oo_guard);
2804         ldiskfs_inc_count(oh->ot_handle, inode);
2805         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
2806         spin_unlock(&obj->oo_guard);
2807
2808         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2809         LINVRNT(osd_invariant(obj));
2810
2811         return rc;
2812 }
2813
2814 static int osd_declare_object_ref_del(const struct lu_env *env,
2815                                       struct dt_object *dt,
2816                                       struct thandle *handle)
2817 {
2818         struct osd_thandle *oh;
2819
2820         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2821         LASSERT(handle != NULL);
2822
2823         oh = container_of0(handle, struct osd_thandle, ot_super);
2824         LASSERT(oh->ot_handle == NULL);
2825
2826         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
2827                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2828
2829         return 0;
2830 }
2831
2832 /*
2833  * Concurrency: @dt is write locked.
2834  */
2835 static int osd_object_ref_del(const struct lu_env *env, struct dt_object *dt,
2836                               struct thandle *th)
2837 {
2838         struct osd_object       *obj = osd_dt_obj(dt);
2839         struct inode            *inode = obj->oo_inode;
2840         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
2841         struct osd_thandle      *oh;
2842
2843         LINVRNT(osd_invariant(obj));
2844         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2845         LASSERT(osd_write_locked(env, obj));
2846         LASSERT(th != NULL);
2847
2848         oh = container_of0(th, struct osd_thandle, ot_super);
2849         LASSERT(oh->ot_handle != NULL);
2850
2851         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
2852
2853         spin_lock(&obj->oo_guard);
2854         /* That can be result of upgrade from old Lustre version and
2855          * applied only to local files.  Just skip this ref_del call.
2856          * ext4_unlink() only treats this as a warning, don't LASSERT here.*/
2857         if (inode->i_nlink == 0) {
2858                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
2859                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
2860                              ", maybe an upgraded file? (LU-3915)\n",
2861                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
2862                 spin_unlock(&obj->oo_guard);
2863                 return 0;
2864         }
2865
2866         ldiskfs_dec_count(oh->ot_handle, inode);
2867         spin_unlock(&obj->oo_guard);
2868
2869         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2870         LINVRNT(osd_invariant(obj));
2871
2872         return 0;
2873 }
2874
2875 /*
2876  * Get the 64-bit version for an inode.
2877  */
2878 static int osd_object_version_get(const struct lu_env *env,
2879                                   struct dt_object *dt, dt_obj_version_t *ver)
2880 {
2881         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2882
2883         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
2884                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2885         *ver = LDISKFS_I(inode)->i_fs_version;
2886         return 0;
2887 }
2888
2889 /*
2890  * Concurrency: @dt is read locked.
2891  */
2892 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
2893                          struct lu_buf *buf, const char *name,
2894                          struct lustre_capa *capa)
2895 {
2896         struct osd_object      *obj    = osd_dt_obj(dt);
2897         struct inode           *inode  = obj->oo_inode;
2898         struct osd_thread_info *info   = osd_oti_get(env);
2899         struct dentry          *dentry = &info->oti_obj_dentry;
2900
2901         /* version get is not real XATTR but uses xattr API */
2902         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2903                 /* for version we are just using xattr API but change inode
2904                  * field instead */
2905                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2906                 osd_object_version_get(env, dt, buf->lb_buf);
2907                 return sizeof(dt_obj_version_t);
2908         }
2909
2910         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2911         LASSERT(inode->i_op != NULL && inode->i_op->getxattr != NULL);
2912
2913         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2914                 return -EACCES;
2915
2916         return __osd_xattr_get(inode, dentry, name, buf->lb_buf, buf->lb_len);
2917 }
2918
2919
2920 static int osd_declare_xattr_set(const struct lu_env *env,
2921                                  struct dt_object *dt,
2922                                  const struct lu_buf *buf, const char *name,
2923                                  int fl, struct thandle *handle)
2924 {
2925         struct osd_thandle *oh;
2926         int credits;
2927
2928         LASSERT(handle != NULL);
2929
2930         oh = container_of0(handle, struct osd_thandle, ot_super);
2931         LASSERT(oh->ot_handle == NULL);
2932
2933         /* optimistic optimization: LMA is set first and usually fit inode */
2934         if (strcmp(name, XATTR_NAME_LMA) == 0) {
2935                 if (dt_object_exists(dt))
2936                         credits = 0;
2937                 else
2938                         credits = 1;
2939         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2940                 credits = 1;
2941         } else {
2942                 struct osd_device  *osd = osd_dev(dt->do_lu.lo_dev);
2943                 struct super_block *sb = osd_sb(osd);
2944                 credits = osd_dto_credits_noquota[DTO_XATTR_SET];
2945                 if (buf && buf->lb_len > sb->s_blocksize) {
2946                         credits *= (buf->lb_len + sb->s_blocksize - 1) >>
2947                                         sb->s_blocksize_bits;
2948                 }
2949         }
2950
2951         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
2952
2953         return 0;
2954 }
2955
2956 /*
2957  * Set the 64-bit version for object
2958  */
2959 static void osd_object_version_set(const struct lu_env *env,
2960                                    struct dt_object *dt,
2961                                    dt_obj_version_t *new_version)
2962 {
2963         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2964
2965         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
2966                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2967
2968         LDISKFS_I(inode)->i_fs_version = *new_version;
2969         /** Version is set after all inode operations are finished,
2970          *  so we should mark it dirty here */
2971         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2972 }
2973
2974 /*
2975  * Concurrency: @dt is write locked.
2976  */
2977 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
2978                          const struct lu_buf *buf, const char *name, int fl,
2979                          struct thandle *handle, struct lustre_capa *capa)
2980 {
2981         struct osd_object      *obj      = osd_dt_obj(dt);
2982         struct inode           *inode    = obj->oo_inode;
2983         struct osd_thread_info *info     = osd_oti_get(env);
2984         int                     fs_flags = 0;
2985         ENTRY;
2986
2987         LASSERT(handle != NULL);
2988
2989         /* version set is not real XATTR */
2990         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2991                 /* for version we are just using xattr API but change inode
2992                  * field instead */
2993                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2994                 osd_object_version_set(env, dt, buf->lb_buf);
2995                 return sizeof(dt_obj_version_t);
2996         }
2997
2998         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2999                 return -EACCES;
3000
3001         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zd\n",
3002                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
3003
3004         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3005         if (fl & LU_XATTR_REPLACE)
3006                 fs_flags |= XATTR_REPLACE;
3007
3008         if (fl & LU_XATTR_CREATE)
3009                 fs_flags |= XATTR_CREATE;
3010
3011         return __osd_xattr_set(info, inode, name, buf->lb_buf, buf->lb_len,
3012                                fs_flags);
3013 }
3014
3015 /*
3016  * Concurrency: @dt is read locked.
3017  */
3018 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
3019                           struct lu_buf *buf, struct lustre_capa *capa)
3020 {
3021         struct osd_object      *obj    = osd_dt_obj(dt);
3022         struct inode           *inode  = obj->oo_inode;
3023         struct osd_thread_info *info   = osd_oti_get(env);
3024         struct dentry          *dentry = &info->oti_obj_dentry;
3025
3026         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3027         LASSERT(inode->i_op != NULL && inode->i_op->listxattr != NULL);
3028
3029         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
3030                 return -EACCES;
3031
3032         dentry->d_inode = inode;
3033         dentry->d_sb = inode->i_sb;
3034         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
3035 }
3036
3037 static int osd_declare_xattr_del(const struct lu_env *env,
3038                                  struct dt_object *dt, const char *name,
3039                                  struct thandle *handle)
3040 {
3041         struct osd_thandle *oh;
3042
3043         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3044         LASSERT(handle != NULL);
3045
3046         oh = container_of0(handle, struct osd_thandle, ot_super);
3047         LASSERT(oh->ot_handle == NULL);
3048
3049         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
3050                              osd_dto_credits_noquota[DTO_XATTR_SET]);
3051
3052         return 0;
3053 }
3054
3055 /*
3056  * Concurrency: @dt is write locked.
3057  */
3058 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
3059                          const char *name, struct thandle *handle,
3060                          struct lustre_capa *capa)
3061 {
3062         struct osd_object      *obj    = osd_dt_obj(dt);
3063         struct inode           *inode  = obj->oo_inode;
3064         struct osd_thread_info *info   = osd_oti_get(env);
3065         struct dentry          *dentry = &info->oti_obj_dentry;
3066         int                     rc;
3067
3068         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3069         LASSERT(inode->i_op != NULL && inode->i_op->removexattr != NULL);
3070         LASSERT(handle != NULL);
3071
3072         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
3073                 return -EACCES;
3074
3075         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3076
3077         ll_vfs_dq_init(inode);
3078         dentry->d_inode = inode;
3079         dentry->d_sb = inode->i_sb;
3080         rc = inode->i_op->removexattr(dentry, name);
3081         return rc;
3082 }
3083
3084 static struct obd_capa *osd_capa_get(const struct lu_env *env,
3085                                      struct dt_object *dt,
3086                                      struct lustre_capa *old, __u64 opc)
3087 {
3088         struct osd_thread_info *info = osd_oti_get(env);
3089         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3090         struct osd_object *obj = osd_dt_obj(dt);
3091         struct osd_device *osd = osd_obj2dev(obj);
3092         struct lustre_capa_key *key = &info->oti_capa_key;
3093         struct lustre_capa *capa = &info->oti_capa;
3094         struct obd_capa *oc;
3095         struct lu_capainfo *lci;
3096         int rc;
3097         ENTRY;
3098
3099         if (!osd->od_fl_capa)
3100                 RETURN(ERR_PTR(-ENOENT));
3101
3102         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3103         LINVRNT(osd_invariant(obj));
3104
3105         /* renewal sanity check */
3106         if (old && osd_object_auth(env, dt, old, opc))
3107                 RETURN(ERR_PTR(-EACCES));
3108
3109         lci = lu_capainfo_get(env);
3110         if (unlikely(lci == NULL))
3111                 RETURN(ERR_PTR(-ENOENT));
3112
3113         switch (lci->lci_auth) {
3114         case LC_ID_NONE:
3115                 RETURN(NULL);
3116         case LC_ID_PLAIN:
3117                 capa->lc_uid = obj->oo_inode->i_uid;
3118                 capa->lc_gid = obj->oo_inode->i_gid;
3119                 capa->lc_flags = LC_ID_PLAIN;
3120                 break;
3121         case LC_ID_CONVERT: {
3122                 __u32 d[4], s[4];
3123
3124                 s[0] = obj->oo_inode->i_uid;
3125                 cfs_get_random_bytes(&(s[1]), sizeof(__u32));
3126                 s[2] = obj->oo_inode->i_gid;
3127                 cfs_get_random_bytes(&(s[3]), sizeof(__u32));
3128                 rc = capa_encrypt_id(d, s, key->lk_key, CAPA_HMAC_KEY_MAX_LEN);
3129                 if (unlikely(rc))
3130                         RETURN(ERR_PTR(rc));
3131
3132                 capa->lc_uid   = ((__u64)d[1] << 32) | d[0];
3133                 capa->lc_gid   = ((__u64)d[3] << 32) | d[2];
3134                 capa->lc_flags = LC_ID_CONVERT;
3135                 break;
3136         }
3137         default:
3138                 RETURN(ERR_PTR(-EINVAL));
3139         }
3140
3141         capa->lc_fid = *fid;
3142         capa->lc_opc = opc;
3143         capa->lc_flags |= osd->od_capa_alg << 24;
3144         capa->lc_timeout = osd->od_capa_timeout;
3145         capa->lc_expiry = 0;
3146
3147         oc = capa_lookup(osd->od_capa_hash, capa, 1);
3148         if (oc) {
3149                 LASSERT(!capa_is_expired(oc));
3150                 RETURN(oc);
3151         }
3152
3153         spin_lock(&capa_lock);
3154         *key = osd->od_capa_keys[1];
3155         spin_unlock(&capa_lock);
3156
3157         capa->lc_keyid = key->lk_keyid;
3158         capa->lc_expiry = cfs_time_current_sec() + osd->od_capa_timeout;
3159
3160         rc = capa_hmac(capa->lc_hmac, capa, key->lk_key);
3161         if (rc) {
3162                 DEBUG_CAPA(D_ERROR, capa, "HMAC failed: %d for", rc);
3163                 RETURN(ERR_PTR(rc));
3164         }
3165
3166         oc = capa_add(osd->od_capa_hash, capa);
3167         RETURN(oc);
3168 }
3169
3170 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt)
3171 {
3172         struct osd_object       *obj    = osd_dt_obj(dt);
3173         struct inode            *inode  = obj->oo_inode;
3174         struct osd_thread_info  *info   = osd_oti_get(env);
3175         struct dentry           *dentry = &info->oti_obj_dentry;
3176         struct file             *file   = &info->oti_file;
3177         int                     rc;
3178
3179         ENTRY;
3180
3181         dentry->d_inode = inode;
3182         dentry->d_sb = inode->i_sb;
3183         file->f_dentry = dentry;
3184         file->f_mapping = inode->i_mapping;
3185         file->f_op = inode->i_fop;
3186         set_file_inode(file, inode);
3187 #ifndef HAVE_FILE_FSYNC_4ARGS
3188         mutex_lock(&inode->i_mutex);
3189 #endif
3190         rc = do_fsync(file, 0);
3191 #ifndef HAVE_FILE_FSYNC_4ARGS
3192         mutex_unlock(&inode->i_mutex);
3193 #endif
3194         RETURN(rc);
3195 }
3196
3197 static int osd_data_get(const struct lu_env *env, struct dt_object *dt,
3198                         void **data)
3199 {
3200         struct osd_object *obj = osd_dt_obj(dt);
3201         ENTRY;
3202
3203         *data = (void *)obj->oo_inode;
3204         RETURN(0);
3205 }
3206
3207 /*
3208  * Index operations.
3209  */
3210
3211 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
3212                            const struct dt_index_features *feat)
3213 {
3214         struct iam_descr *descr;
3215
3216         if (osd_object_is_root(o))
3217                 return feat == &dt_directory_features;
3218
3219         LASSERT(o->oo_dir != NULL);
3220
3221         descr = o->oo_dir->od_container.ic_descr;
3222         if (feat == &dt_directory_features) {
3223                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
3224                         return 1;
3225                 else
3226                         return 0;
3227         } else {
3228                 return
3229                         feat->dif_keysize_min <= descr->id_key_size &&
3230                         descr->id_key_size <= feat->dif_keysize_max &&
3231                         feat->dif_recsize_min <= descr->id_rec_size &&
3232                         descr->id_rec_size <= feat->dif_recsize_max &&
3233                         !(feat->dif_flags & (DT_IND_VARKEY |
3234                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
3235                         ergo(feat->dif_flags & DT_IND_UPDATE,
3236                              1 /* XXX check that object (and file system) is
3237                                 * writable */);
3238         }
3239 }
3240
3241 static int osd_iam_container_init(const struct lu_env *env,
3242                                   struct osd_object *obj,
3243                                   struct osd_directory *dir)
3244 {
3245         struct iam_container *bag = &dir->od_container;
3246         int result;
3247
3248         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
3249         if (result != 0)
3250                 return result;
3251
3252         result = iam_container_setup(bag);
3253         if (result == 0)
3254                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
3255         else
3256                 iam_container_fini(bag);
3257
3258         return result;
3259 }
3260
3261
3262 /*
3263  * Concurrency: no external locking is necessary.
3264  */
3265 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
3266                          const struct dt_index_features *feat)
3267 {
3268         int                      result;
3269         int                      skip_iam = 0;
3270         struct osd_object       *obj = osd_dt_obj(dt);
3271
3272         LINVRNT(osd_invariant(obj));
3273
3274         if (osd_object_is_root(obj)) {
3275                 dt->do_index_ops = &osd_index_ea_ops;
3276                 result = 0;
3277         } else if (feat == &dt_directory_features) {
3278                 dt->do_index_ops = &osd_index_ea_ops;
3279                 if (obj->oo_inode != NULL && S_ISDIR(obj->oo_inode->i_mode))
3280                         result = 0;
3281                 else
3282                         result = -ENOTDIR;
3283                 skip_iam = 1;
3284         } else if (unlikely(feat == &dt_otable_features)) {
3285                 dt->do_index_ops = &osd_otable_ops;
3286                 return 0;
3287         } else if (unlikely(feat == &dt_acct_features)) {
3288                 dt->do_index_ops = &osd_acct_index_ops;
3289                 result = 0;
3290                 skip_iam = 1;
3291         } else if (!osd_has_index(obj)) {
3292                 struct osd_directory *dir;
3293
3294                 OBD_ALLOC_PTR(dir);
3295                 if (dir != NULL) {
3296
3297                         spin_lock(&obj->oo_guard);
3298                         if (obj->oo_dir == NULL)
3299                                 obj->oo_dir = dir;
3300                         else
3301                                 /*
3302                                  * Concurrent thread allocated container data.
3303                                  */
3304                                 OBD_FREE_PTR(dir);
3305                         spin_unlock(&obj->oo_guard);
3306                         /*
3307                          * Now, that we have container data, serialize its
3308                          * initialization.
3309                          */
3310                         down_write(&obj->oo_ext_idx_sem);
3311                         /*
3312                          * recheck under lock.
3313                          */
3314                         if (!osd_has_index(obj))
3315                                 result = osd_iam_container_init(env, obj, dir);
3316                         else
3317                                 result = 0;
3318                         up_write(&obj->oo_ext_idx_sem);
3319                 } else {
3320                         result = -ENOMEM;
3321                 }
3322         } else {
3323                 result = 0;
3324         }
3325
3326         if (result == 0 && skip_iam == 0) {
3327                 if (!osd_iam_index_probe(env, obj, feat))
3328                         result = -ENOTDIR;
3329         }
3330         LINVRNT(osd_invariant(obj));
3331
3332         if (result == 0 && is_quota_glb_feat(feat) &&
3333             fid_seq(lu_object_fid(&dt->do_lu)) == FID_SEQ_QUOTA_GLB)
3334                 result = osd_quota_migration(env, dt, feat);
3335
3336         return result;
3337 }
3338
3339 static int osd_otable_it_attr_get(const struct lu_env *env,
3340                                  struct dt_object *dt,
3341                                  struct lu_attr *attr,
3342                                  struct lustre_capa *capa)
3343 {
3344         attr->la_valid = 0;
3345         return 0;
3346 }
3347
3348 static const struct dt_object_operations osd_obj_ops = {
3349         .do_read_lock         = osd_object_read_lock,
3350         .do_write_lock        = osd_object_write_lock,
3351         .do_read_unlock       = osd_object_read_unlock,
3352         .do_write_unlock      = osd_object_write_unlock,
3353         .do_write_locked      = osd_object_write_locked,
3354         .do_attr_get          = osd_attr_get,
3355         .do_declare_attr_set  = osd_declare_attr_set,
3356         .do_attr_set          = osd_attr_set,
3357         .do_ah_init           = osd_ah_init,
3358         .do_declare_create    = osd_declare_object_create,
3359         .do_create            = osd_object_create,
3360         .do_declare_destroy   = osd_declare_object_destroy,
3361         .do_destroy           = osd_object_destroy,
3362         .do_index_try         = osd_index_try,
3363         .do_declare_ref_add   = osd_declare_object_ref_add,
3364         .do_ref_add           = osd_object_ref_add,
3365         .do_declare_ref_del   = osd_declare_object_ref_del,
3366         .do_ref_del           = osd_object_ref_del,
3367         .do_xattr_get         = osd_xattr_get,
3368         .do_declare_xattr_set = osd_declare_xattr_set,
3369         .do_xattr_set         = osd_xattr_set,
3370         .do_declare_xattr_del = osd_declare_xattr_del,
3371         .do_xattr_del         = osd_xattr_del,
3372         .do_xattr_list        = osd_xattr_list,
3373         .do_capa_get          = osd_capa_get,
3374         .do_object_sync       = osd_object_sync,
3375         .do_data_get          = osd_data_get,
3376 };
3377
3378 /**
3379  * dt_object_operations for interoperability mode
3380  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
3381  */
3382 static const struct dt_object_operations osd_obj_ea_ops = {
3383         .do_read_lock         = osd_object_read_lock,
3384         .do_write_lock        = osd_object_write_lock,
3385         .do_read_unlock       = osd_object_read_unlock,
3386         .do_write_unlock      = osd_object_write_unlock,
3387         .do_write_locked      = osd_object_write_locked,
3388         .do_attr_get          = osd_attr_get,
3389         .do_declare_attr_set  = osd_declare_attr_set,
3390         .do_attr_set          = osd_attr_set,
3391         .do_ah_init           = osd_ah_init,
3392         .do_declare_create    = osd_declare_object_create,
3393         .do_create            = osd_object_ea_create,
3394         .do_declare_destroy   = osd_declare_object_destroy,
3395         .do_destroy           = osd_object_destroy,
3396         .do_index_try         = osd_index_try,
3397         .do_declare_ref_add   = osd_declare_object_ref_add,
3398         .do_ref_add           = osd_object_ref_add,
3399         .do_declare_ref_del   = osd_declare_object_ref_del,
3400         .do_ref_del           = osd_object_ref_del,
3401         .do_xattr_get         = osd_xattr_get,
3402         .do_declare_xattr_set = osd_declare_xattr_set,
3403         .do_xattr_set         = osd_xattr_set,
3404         .do_declare_xattr_del = osd_declare_xattr_del,
3405         .do_xattr_del         = osd_xattr_del,
3406         .do_xattr_list        = osd_xattr_list,
3407         .do_capa_get          = osd_capa_get,
3408         .do_object_sync       = osd_object_sync,
3409         .do_data_get          = osd_data_get,
3410 };
3411
3412 static const struct dt_object_operations osd_obj_otable_it_ops = {
3413         .do_attr_get    = osd_otable_it_attr_get,
3414         .do_index_try   = osd_index_try,
3415 };
3416
3417 static int osd_index_declare_iam_delete(const struct lu_env *env,
3418                                         struct dt_object *dt,
3419                                         const struct dt_key *key,
3420                                         struct thandle *handle)
3421 {
3422         struct osd_thandle    *oh;
3423
3424         oh = container_of0(handle, struct osd_thandle, ot_super);
3425         LASSERT(oh->ot_handle == NULL);
3426
3427         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3428                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3429
3430         return 0;
3431 }
3432
3433 /**
3434  *      delete a (key, value) pair from index \a dt specified by \a key
3435  *
3436  *      \param  dt      osd index object
3437  *      \param  key     key for index
3438  *      \param  rec     record reference
3439  *      \param  handle  transaction handler
3440  *
3441  *      \retval  0  success
3442  *      \retval -ve   failure
3443  */
3444
3445 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
3446                                 const struct dt_key *key,
3447                                 struct thandle *handle,
3448                                 struct lustre_capa *capa)
3449 {
3450         struct osd_thread_info *oti = osd_oti_get(env);
3451         struct osd_object      *obj = osd_dt_obj(dt);
3452         struct osd_thandle     *oh;
3453         struct iam_path_descr  *ipd;
3454         struct iam_container   *bag = &obj->oo_dir->od_container;
3455         int                     rc;
3456
3457         ENTRY;
3458
3459         LINVRNT(osd_invariant(obj));
3460         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3461         LASSERT(bag->ic_object == obj->oo_inode);
3462         LASSERT(handle != NULL);
3463
3464         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3465                 RETURN(-EACCES);
3466
3467         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3468
3469         ipd = osd_idx_ipd_get(env, bag);
3470         if (unlikely(ipd == NULL))
3471                 RETURN(-ENOMEM);
3472
3473         oh = container_of0(handle, struct osd_thandle, ot_super);
3474         LASSERT(oh->ot_handle != NULL);
3475         LASSERT(oh->ot_handle->h_transaction != NULL);
3476
3477         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3478                 /* swab quota uid/gid provided by caller */
3479                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3480                 key = (const struct dt_key *)&oti->oti_quota_id;
3481         }
3482
3483         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
3484         osd_ipd_put(env, bag, ipd);
3485         LINVRNT(osd_invariant(obj));
3486         RETURN(rc);
3487 }
3488
3489 static int osd_index_declare_ea_delete(const struct lu_env *env,
3490                                        struct dt_object *dt,
3491                                        const struct dt_key *key,
3492                                        struct thandle *handle)
3493 {
3494         struct osd_thandle *oh;
3495         struct inode       *inode;
3496         int                 rc;
3497         ENTRY;
3498
3499         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3500         LASSERT(handle != NULL);
3501
3502         oh = container_of0(handle, struct osd_thandle, ot_super);
3503         LASSERT(oh->ot_handle == NULL);
3504
3505         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3506                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3507
3508         inode = osd_dt_obj(dt)->oo_inode;
3509         LASSERT(inode);
3510
3511         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
3512                                    true, true, NULL, false);
3513         RETURN(rc);
3514 }
3515
3516 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3517                                           struct dt_rec *fid)
3518 {
3519         struct osd_fid_pack *rec;
3520         int                  rc = -ENODATA;
3521
3522         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3523                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3524                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3525         }
3526         return rc;
3527 }
3528
3529 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
3530                           struct lu_fid *fid)
3531 {
3532         ENTRY;
3533
3534         /* FID seqs not in FLDB, must be local seq */
3535         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
3536                 RETURN(0);
3537
3538         if (osd_seq_exists(env, osd, fid_seq(fid)))
3539                 RETURN(0);
3540
3541         RETURN(1);
3542 }
3543
3544 /**
3545  * Index delete function for interoperability mode (b11826).
3546  * It will remove the directory entry added by osd_index_ea_insert().
3547  * This entry is needed to maintain name->fid mapping.
3548  *
3549  * \param key,  key i.e. file entry to be deleted
3550  *
3551  * \retval   0, on success
3552  * \retval -ve, on error
3553  */
3554 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3555                                const struct dt_key *key,
3556                                struct thandle *handle,
3557                                struct lustre_capa *capa)
3558 {
3559         struct osd_object          *obj    = osd_dt_obj(dt);
3560         struct inode               *dir    = obj->oo_inode;
3561         struct dentry              *dentry;
3562         struct osd_thandle         *oh;
3563         struct ldiskfs_dir_entry_2 *de = NULL;
3564         struct buffer_head         *bh;
3565         struct htree_lock          *hlock = NULL;
3566         struct lu_fid              *fid = &osd_oti_get(env)->oti_fid;
3567         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
3568         int                        rc;
3569         ENTRY;
3570
3571         LINVRNT(osd_invariant(obj));
3572         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3573         LASSERT(handle != NULL);
3574
3575         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3576
3577         oh = container_of(handle, struct osd_thandle, ot_super);
3578         LASSERT(oh->ot_handle != NULL);
3579         LASSERT(oh->ot_handle->h_transaction != NULL);
3580
3581         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3582                 RETURN(-EACCES);
3583
3584         ll_vfs_dq_init(dir);
3585         dentry = osd_child_dentry_get(env, obj,
3586                                       (char *)key, strlen((char *)key));
3587
3588         if (obj->oo_hl_head != NULL) {
3589                 hlock = osd_oti_get(env)->oti_hlock;
3590                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3591                                    dir, LDISKFS_HLOCK_DEL);
3592         } else {
3593                 down_write(&obj->oo_ext_idx_sem);
3594         }
3595
3596         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
3597         if (bh) {
3598                 __u32 ino = 0;
3599
3600                 /* If this is not the ".." entry, it might be a remote DNE
3601                  * entry and  we need to check if the FID is for a remote
3602                  * MDT.  If the FID is  not in the directory entry (e.g.
3603                  * upgraded 1.8 filesystem without dirdata enabled) then
3604                  * we need to get the FID from the LMA. For a remote directory
3605                  * there HAS to be an LMA, it cannot be an IGIF inode in this
3606                  * case.
3607                  *
3608                  * Delete the entry before the agent inode in order to
3609                  * simplify error handling.  At worst an error after deleting
3610                  * the entry first might leak the agent inode afterward. The
3611                  * reverse would need filesystem abort in case of error deleting
3612                  * the entry after the agent had been removed, or leave a
3613                  * dangling entry pointing at a random inode. */
3614                 if (strcmp((char *)key, dotdot) != 0) {
3615                         LASSERT(de != NULL);
3616                         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
3617                         /* If Fid is not in dentry, try to get it from LMA */
3618                         if (rc == -ENODATA) {
3619                                 struct osd_inode_id *id;
3620                                 struct inode *inode;
3621
3622                                 /* Before trying to get fid from the inode,
3623                                  * check whether the inode is valid.
3624                                  *
3625                                  * If the inode has been deleted, do not go
3626                                  * ahead to do osd_ea_fid_get, which will set
3627                                  * the inode to bad inode, which might cause
3628                                  * the inode to be deleted uncorrectly */
3629                                 inode = ldiskfs_iget(osd_sb(osd),
3630                                                      le32_to_cpu(de->inode));
3631                                 if (IS_ERR(inode)) {
3632                                         CDEBUG(D_INODE, "%s: "DFID"get inode"
3633                                                "error.\n", osd_name(osd),
3634                                                PFID(fid));
3635                                         rc = PTR_ERR(inode);
3636                                 } else {
3637                                         if (likely(inode->i_nlink != 0)) {
3638                                                 id = &osd_oti_get(env)->oti_id;
3639                                                 rc = osd_ea_fid_get(env, obj,
3640                                                         le32_to_cpu(de->inode),
3641                                                                     fid, id);
3642                                         } else {
3643                                                 CDEBUG(D_INFO, "%s: %u "DFID
3644                                                        "deleted.\n",
3645                                                        osd_name(osd),
3646                                                        le32_to_cpu(de->inode),
3647                                                        PFID(fid));
3648                                                 rc = -ESTALE;
3649                                         }
3650                                         iput(inode);
3651                                 }
3652                         }
3653                         if (rc == 0 &&
3654                             unlikely(osd_remote_fid(env, osd, fid)))
3655                                 /* Need to delete agent inode */
3656                                 ino = le32_to_cpu(de->inode);
3657                 }
3658                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
3659                 brelse(bh);
3660                 if (rc == 0 && unlikely(ino != 0)) {
3661                         rc = osd_delete_local_agent_inode(env, osd, fid, ino,
3662                                                           oh);
3663                         if (rc != 0)
3664                                 CERROR("%s: del local inode "DFID": rc = %d\n",
3665                                        osd_name(osd), PFID(fid), rc);
3666                 }
3667         } else {
3668                 rc = -ENOENT;
3669         }
3670         if (hlock != NULL)
3671                 ldiskfs_htree_unlock(hlock);
3672         else
3673                 up_write(&obj->oo_ext_idx_sem);
3674
3675         if (rc != 0)
3676                 GOTO(out, rc);
3677
3678         /* For inode on the remote MDT, .. will point to
3679          * /Agent directory, Check whether it needs to delete
3680          * from agent directory */
3681         if (unlikely(strcmp((char *)key, dotdot) == 0)) {
3682                 rc = osd_delete_from_remote_parent(env, osd_obj2dev(obj), obj,
3683                                                    oh);
3684                 if (rc != 0 && rc != -ENOENT) {
3685                         CERROR("%s: delete agent inode "DFID": rc = %d\n",
3686                                osd_name(osd), PFID(fid), rc);
3687                 }
3688
3689                 if (rc == -ENOENT)
3690                         rc = 0;
3691
3692                 GOTO(out, rc);
3693         }
3694 out:
3695
3696         LASSERT(osd_invariant(obj));
3697         RETURN(rc);
3698 }
3699
3700 /**
3701  *      Lookup index for \a key and copy record to \a rec.
3702  *
3703  *      \param  dt      osd index object
3704  *      \param  key     key for index
3705  *      \param  rec     record reference
3706  *
3707  *      \retval  +ve  success : exact mach
3708  *      \retval  0    return record with key not greater than \a key
3709  *      \retval -ve   failure
3710  */
3711 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
3712                                 struct dt_rec *rec, const struct dt_key *key,
3713                                 struct lustre_capa *capa)
3714 {
3715         struct osd_object      *obj = osd_dt_obj(dt);
3716         struct iam_path_descr  *ipd;
3717         struct iam_container   *bag = &obj->oo_dir->od_container;
3718         struct osd_thread_info *oti = osd_oti_get(env);
3719         struct iam_iterator    *it = &oti->oti_idx_it;
3720         struct iam_rec         *iam_rec;
3721         int                     rc;
3722
3723         ENTRY;
3724
3725         LASSERT(osd_invariant(obj));
3726         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3727         LASSERT(bag->ic_object == obj->oo_inode);
3728
3729         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
3730                 RETURN(-EACCES);
3731
3732         ipd = osd_idx_ipd_get(env, bag);
3733         if (IS_ERR(ipd))
3734                 RETURN(-ENOMEM);
3735
3736         /* got ipd now we can start iterator. */
3737         iam_it_init(it, bag, 0, ipd);
3738
3739         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3740                 /* swab quota uid/gid provided by caller */
3741                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3742                 key = (const struct dt_key *)&oti->oti_quota_id;
3743         }
3744
3745         rc = iam_it_get(it, (struct iam_key *)key);
3746         if (rc >= 0) {
3747                 if (S_ISDIR(obj->oo_inode->i_mode))
3748                         iam_rec = (struct iam_rec *)oti->oti_ldp;
3749                 else
3750                         iam_rec = (struct iam_rec *) rec;
3751
3752                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
3753
3754                 if (S_ISDIR(obj->oo_inode->i_mode))
3755                         osd_fid_unpack((struct lu_fid *) rec,
3756                                        (struct osd_fid_pack *)iam_rec);
3757                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
3758                         osd_quota_unpack(obj, rec);
3759         }
3760
3761         iam_it_put(it);
3762         iam_it_fini(it);
3763         osd_ipd_put(env, bag, ipd);
3764
3765         LINVRNT(osd_invariant(obj));
3766
3767         RETURN(rc);
3768 }
3769
3770 static int osd_index_declare_iam_insert(const struct lu_env *env,
3771                                         struct dt_object *dt,
3772                                         const struct dt_rec *rec,
3773                                         const struct dt_key *key,
3774                                         struct thandle *handle)
3775 {
3776         struct osd_thandle *oh;
3777
3778         LASSERT(handle != NULL);
3779
3780         oh = container_of0(handle, struct osd_thandle, ot_super);
3781         LASSERT(oh->ot_handle == NULL);
3782
3783         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3784                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
3785
3786         return 0;
3787 }
3788
3789 /**
3790  *      Inserts (key, value) pair in \a dt index object.
3791  *
3792  *      \param  dt      osd index object
3793  *      \param  key     key for index
3794  *      \param  rec     record reference
3795  *      \param  th      transaction handler
3796  *
3797  *      \retval  0  success
3798  *      \retval -ve failure
3799  */
3800 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
3801                                 const struct dt_rec *rec,
3802                                 const struct dt_key *key, struct thandle *th,
3803                                 struct lustre_capa *capa, int ignore_quota)
3804 {
3805         struct osd_object     *obj = osd_dt_obj(dt);
3806         struct iam_path_descr *ipd;
3807         struct osd_thandle    *oh;
3808         struct iam_container  *bag = &obj->oo_dir->od_container;
3809         struct osd_thread_info *oti = osd_oti_get(env);
3810         struct iam_rec         *iam_rec;
3811         int                     rc;
3812
3813         ENTRY;
3814
3815         LINVRNT(osd_invariant(obj));
3816         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3817         LASSERT(bag->ic_object == obj->oo_inode);
3818         LASSERT(th != NULL);
3819
3820         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3821                 RETURN(-EACCES);
3822
3823         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3824
3825         ipd = osd_idx_ipd_get(env, bag);
3826         if (unlikely(ipd == NULL))
3827                 RETURN(-ENOMEM);
3828
3829         oh = container_of0(th, struct osd_thandle, ot_super);
3830         LASSERT(oh->ot_handle != NULL);
3831         LASSERT(oh->ot_handle->h_transaction != NULL);
3832         if (S_ISDIR(obj->oo_inode->i_mode)) {
3833                 iam_rec = (struct iam_rec *)oti->oti_ldp;
3834                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
3835         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3836                 /* pack quota uid/gid */
3837                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3838                 key = (const struct dt_key *)&oti->oti_quota_id;
3839                 /* pack quota record */
3840                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
3841                 iam_rec = (struct iam_rec *)rec;
3842         } else {
3843                 iam_rec = (struct iam_rec *)rec;
3844         }
3845
3846         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
3847                         iam_rec, ipd);
3848         osd_ipd_put(env, bag, ipd);
3849         LINVRNT(osd_invariant(obj));
3850         RETURN(rc);
3851 }
3852
3853 /**
3854  * Calls ldiskfs_add_entry() to add directory entry
3855  * into the directory. This is required for
3856  * interoperability mode (b11826)
3857  *
3858  * \retval   0, on success
3859  * \retval -ve, on error
3860  */
3861 static int __osd_ea_add_rec(struct osd_thread_info *info,
3862                             struct osd_object *pobj, struct inode  *cinode,
3863                             const char *name, const struct dt_rec *fid,
3864                             struct htree_lock *hlock, struct thandle *th)
3865 {
3866         struct ldiskfs_dentry_param *ldp;
3867         struct dentry               *child;
3868         struct osd_thandle          *oth;
3869         int                          rc;
3870
3871         oth = container_of(th, struct osd_thandle, ot_super);
3872         LASSERT(oth->ot_handle != NULL);
3873         LASSERT(oth->ot_handle->h_transaction != NULL);
3874         LASSERT(pobj->oo_inode);
3875
3876         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3877         if (unlikely(pobj->oo_inode ==
3878                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
3879                 ldp->edp_magic = 0;
3880         else
3881                 osd_get_ldiskfs_dirent_param(ldp, fid);
3882         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
3883         child->d_fsdata = (void *)ldp;
3884         ll_vfs_dq_init(pobj->oo_inode);
3885         rc = osd_ldiskfs_add_entry(oth->ot_handle, child, cinode, hlock);
3886
3887         RETURN(rc);
3888 }
3889
3890 /**
3891  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
3892  * into the directory.Also sets flags into osd object to
3893  * indicate dot and dotdot are created. This is required for
3894  * interoperability mode (b11826)
3895  *
3896  * \param dir   directory for dot and dotdot fixup.
3897  * \param obj   child object for linking
3898  *
3899  * \retval   0, on success
3900  * \retval -ve, on error
3901  */
3902 static int osd_add_dot_dotdot(struct osd_thread_info *info,
3903                               struct osd_object *dir,
3904                               struct inode  *parent_dir, const char *name,
3905                               const struct dt_rec *dot_fid,
3906                               const struct dt_rec *dot_dot_fid,
3907                               struct thandle *th)
3908 {
3909         struct inode                *inode = dir->oo_inode;
3910         struct osd_thandle          *oth;
3911         int result = 0;
3912
3913         oth = container_of(th, struct osd_thandle, ot_super);
3914         LASSERT(oth->ot_handle->h_transaction != NULL);
3915         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
3916
3917         if (strcmp(name, dot) == 0) {
3918                 if (dir->oo_compat_dot_created) {
3919                         result = -EEXIST;
3920                 } else {
3921                         LASSERT(inode == parent_dir);
3922                         dir->oo_compat_dot_created = 1;
3923                         result = 0;
3924                 }
3925         } else if (strcmp(name, dotdot) == 0) {
3926                 if (!dir->oo_compat_dot_created)
3927                         return -EINVAL;
3928                 /* in case of rename, dotdot is already created */
3929                 if (dir->oo_compat_dotdot_created) {
3930                         return __osd_ea_add_rec(info, dir, parent_dir, name,
3931                                                 dot_dot_fid, NULL, th);
3932                 }
3933
3934                 result = osd_add_dot_dotdot_internal(info, dir->oo_inode,
3935                                                 parent_dir, dot_fid,
3936                                                 dot_dot_fid, oth);
3937                 if (result == 0)
3938                         dir->oo_compat_dotdot_created = 1;
3939         }
3940
3941         return result;
3942 }
3943
3944
3945 /**
3946  * It will call the appropriate osd_add* function and return the
3947  * value, return by respective functions.
3948  */
3949 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
3950                           struct inode *cinode, const char *name,
3951                           const struct dt_rec *fid, struct thandle *th)
3952 {
3953         struct osd_thread_info *info   = osd_oti_get(env);
3954         struct htree_lock      *hlock;
3955         int                     rc;
3956
3957         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
3958
3959         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
3960                                                    name[2] =='\0'))) {
3961                 if (hlock != NULL) {
3962                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3963                                            pobj->oo_inode, 0);
3964                 } else {
3965                         down_write(&pobj->oo_ext_idx_sem);
3966                 }
3967                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
3968                      (struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
3969                                         fid, th);
3970         } else {
3971                 if (hlock != NULL) {
3972                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3973                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
3974                 } else {
3975                         down_write(&pobj->oo_ext_idx_sem);
3976                 }
3977
3978                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
3979                         struct lu_fid *tfid = &info->oti_fid;
3980
3981                         *tfid = *(const struct lu_fid *)fid;
3982                         tfid->f_ver = ~0;
3983                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
3984                                               (const struct dt_rec *)tfid,
3985                                               hlock, th);
3986                 } else {
3987                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
3988                                               hlock, th);
3989                 }
3990         }
3991         if (hlock != NULL)
3992                 ldiskfs_htree_unlock(hlock);
3993         else
3994                 up_write(&pobj->oo_ext_idx_sem);
3995
3996         return rc;
3997 }
3998
3999 static void
4000 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
4001                       struct osd_idmap_cache *oic)
4002 {
4003         struct osd_scrub    *scrub = &dev->od_scrub;
4004         struct lu_fid       *fid   = &oic->oic_fid;
4005         struct osd_inode_id *id    = &oti->oti_id;
4006         int                  once  = 0;
4007         int                  rc;
4008         ENTRY;
4009
4010         if (!fid_is_norm(fid) && !fid_is_igif(fid))
4011                 RETURN_EXIT;
4012
4013 again:
4014         rc = osd_oi_lookup(oti, dev, fid, id, OI_CHECK_FLD);
4015         if (rc != 0 && rc != -ENOENT)
4016                 RETURN_EXIT;
4017
4018         if (rc == 0 && osd_id_eq(id, &oic->oic_lid))
4019                 RETURN_EXIT;
4020
4021         if (thread_is_running(&scrub->os_thread)) {
4022                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
4023                 /* There is race condition between osd_oi_lookup and OI scrub.
4024                  * The OI scrub finished just after osd_oi_lookup() failure.
4025                  * Under such case, it is unnecessary to trigger OI scrub again,
4026                  * but try to call osd_oi_lookup() again. */
4027                 if (unlikely(rc == -EAGAIN))
4028                         goto again;
4029
4030                 RETURN_EXIT;
4031         }
4032
4033         if (!dev->od_noscrub && ++once == 1) {
4034                 rc = osd_scrub_start(dev);
4035                 LCONSOLE_WARN("%.16s: trigger OI scrub by RPC for "DFID
4036                               ", rc = %d [2]\n",
4037                               LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
4038                               PFID(fid), rc);
4039                 if (rc == 0)
4040                         goto again;
4041         }
4042
4043         EXIT;
4044 }
4045
4046 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
4047                                struct osd_device *dev,
4048                                struct osd_idmap_cache *oic,
4049                                struct lu_fid *fid, __u32 ino)
4050 {
4051         struct lustre_mdt_attrs *lma   = &oti->oti_mdt_attrs;
4052         struct inode            *inode;
4053         int                      rc;
4054
4055         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
4056         inode = osd_iget(oti, dev, &oic->oic_lid);
4057         if (IS_ERR(inode)) {
4058                 fid_zero(&oic->oic_fid);
4059                 return PTR_ERR(inode);
4060         }
4061
4062         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, lma);
4063         iput(inode);
4064         if (rc != 0)
4065                 fid_zero(&oic->oic_fid);
4066         else
4067                 *fid = oic->oic_fid = lma->lma_self_fid;
4068         return rc;
4069 }
4070
4071 int osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
4072                      struct osd_inode_id *id, const struct lu_fid *fid)
4073 {
4074         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
4075                id->oii_ino, id->oii_gen, info);
4076         info->oti_cache.oic_lid = *id;
4077         info->oti_cache.oic_fid = *fid;
4078         info->oti_cache.oic_dev = osd;
4079
4080         return 0;
4081 }
4082
4083 /**
4084  * Calls ->lookup() to find dentry. From dentry get inode and
4085  * read inode's ea to get fid. This is required for  interoperability
4086  * mode (b11826)
4087  *
4088  * \retval   0, on success
4089  * \retval -ve, on error
4090  */
4091 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
4092                              struct dt_rec *rec, const struct dt_key *key)
4093 {
4094         struct inode               *dir    = obj->oo_inode;
4095         struct dentry              *dentry;
4096         struct ldiskfs_dir_entry_2 *de;
4097         struct buffer_head         *bh;
4098         struct lu_fid              *fid = (struct lu_fid *) rec;
4099         struct htree_lock          *hlock = NULL;
4100         int                         ino;
4101         int                         rc;
4102         ENTRY;
4103
4104         LASSERT(dir->i_op != NULL && dir->i_op->lookup != NULL);
4105
4106         dentry = osd_child_dentry_get(env, obj,
4107                                       (char *)key, strlen((char *)key));
4108
4109         if (obj->oo_hl_head != NULL) {
4110                 hlock = osd_oti_get(env)->oti_hlock;
4111                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4112                                    dir, LDISKFS_HLOCK_LOOKUP);
4113         } else {
4114                 down_read(&obj->oo_ext_idx_sem);
4115         }
4116
4117         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
4118         if (bh) {
4119                 struct osd_thread_info *oti = osd_oti_get(env);
4120                 struct osd_inode_id *id = &oti->oti_id;
4121                 struct osd_idmap_cache *oic = &oti->oti_cache;
4122                 struct osd_device *dev = osd_obj2dev(obj);
4123                 struct osd_scrub *scrub = &dev->od_scrub;
4124                 struct scrub_file *sf = &scrub->os_file;
4125
4126                 ino = le32_to_cpu(de->inode);
4127                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
4128                         brelse(bh);
4129                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
4130                         GOTO(out, rc);
4131                 }
4132
4133                 rc = osd_get_fid_from_dentry(de, rec);
4134
4135                 /* done with de, release bh */
4136                 brelse(bh);
4137                 if (rc != 0)
4138                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
4139                 else
4140                         osd_id_gen(id, ino, OSD_OII_NOGEN);
4141                 if (rc != 0) {
4142                         fid_zero(&oic->oic_fid);
4143                         GOTO(out, rc);
4144                 }
4145
4146                 if (osd_remote_fid(env, dev, fid))
4147                         GOTO(out, rc = 0);
4148
4149                 rc = osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id,
4150                                       fid);
4151                 if (rc != 0)
4152                         GOTO(out, rc);
4153                 if ((scrub->os_pos_current <= ino) &&
4154                     ((sf->sf_flags & SF_INCONSISTENT) ||
4155                      (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
4156                      ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
4157                                       sf->sf_oi_bitmap)))
4158                         osd_consistency_check(oti, dev, oic);
4159         } else {
4160                 rc = -ENOENT;
4161         }
4162
4163         GOTO(out, rc);
4164
4165 out:
4166         if (hlock != NULL)
4167                 ldiskfs_htree_unlock(hlock);
4168         else
4169                 up_read(&obj->oo_ext_idx_sem);
4170         return rc;
4171 }
4172
4173 /**
4174  * Find the osd object for given fid.
4175  *
4176  * \param fid need to find the osd object having this fid
4177  *
4178  * \retval osd_object on success
4179  * \retval        -ve on error
4180  */
4181 struct osd_object *osd_object_find(const struct lu_env *env,
4182                                    struct dt_object *dt,
4183                                    const struct lu_fid *fid)
4184 {
4185         struct lu_device  *ludev = dt->do_lu.lo_dev;
4186         struct osd_object *child = NULL;
4187         struct lu_object  *luch;
4188         struct lu_object  *lo;
4189
4190         /*
4191          * at this point topdev might not exist yet
4192          * (i.e. MGS is preparing profiles). so we can
4193          * not rely on topdev and instead lookup with
4194          * our device passed as topdev. this can't work
4195          * if the object isn't cached yet (as osd doesn't
4196          * allocate lu_header). IOW, the object must be
4197          * in the cache, otherwise lu_object_alloc() crashes
4198          * -bzzz
4199          */
4200         luch = lu_object_find_at(env, ludev->ld_site->ls_top_dev == NULL ?
4201                                  ludev : ludev->ld_site->ls_top_dev,
4202                                  fid, NULL);
4203         if (!IS_ERR(luch)) {
4204                 if (lu_object_exists(luch)) {
4205                         lo = lu_object_locate(luch->lo_header, ludev->ld_type);
4206                         if (lo != NULL)
4207                                 child = osd_obj(lo);
4208                         else
4209                                 LU_OBJECT_DEBUG(D_ERROR, env, luch,
4210                                                 "lu_object can't be located"
4211                                                 DFID"\n", PFID(fid));
4212
4213                         if (child == NULL) {
4214                                 lu_object_put(env, luch);
4215                                 CERROR("Unable to get osd_object\n");
4216                                 child = ERR_PTR(-ENOENT);
4217                         }
4218                 } else {
4219                         LU_OBJECT_DEBUG(D_ERROR, env, luch,
4220                                         "lu_object does not exists "DFID"\n",
4221                                         PFID(fid));
4222                         lu_object_put(env, luch);
4223                         child = ERR_PTR(-ENOENT);
4224                 }
4225         } else {
4226                 child = ERR_CAST(luch);
4227         }
4228
4229         return child;
4230 }
4231
4232 /**
4233  * Put the osd object once done with it.
4234  *
4235  * \param obj osd object that needs to be put
4236  */
4237 static inline void osd_object_put(const struct lu_env *env,
4238                                   struct osd_object *obj)
4239 {
4240         lu_object_put(env, &obj->oo_dt.do_lu);
4241 }
4242
4243 static int osd_index_declare_ea_insert(const struct lu_env *env,
4244                                        struct dt_object *dt,
4245                                        const struct dt_rec *rec,
4246                                        const struct dt_key *key,
4247                                        struct thandle *handle)
4248 {
4249         struct osd_thandle      *oh;
4250         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
4251         struct lu_fid           *fid = (struct lu_fid *)rec;
4252         int                     rc;
4253         ENTRY;
4254
4255         LASSERT(!dt_object_remote(dt));
4256         LASSERT(handle != NULL);
4257
4258         oh = container_of0(handle, struct osd_thandle, ot_super);
4259         LASSERT(oh->ot_handle == NULL);
4260
4261         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4262                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4263
4264         if (osd_dt_obj(dt)->oo_inode == NULL) {
4265                 const char *name  = (const char *)key;
4266                 /* Object is not being created yet. Only happens when
4267                  *     1. declare directory create
4268                  *     2. declare insert .
4269                  *     3. declare insert ..
4270                  */
4271                 LASSERT(strcmp(name, dotdot) == 0 || strcmp(name, dot) == 0);
4272         } else {
4273                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
4274
4275                 /* We ignore block quota on meta pool (MDTs), so needn't
4276                  * calculate how many blocks will be consumed by this index
4277                  * insert */
4278                 rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0,
4279                                            oh, true, true, NULL, false);
4280         }
4281
4282         if (fid == NULL)
4283                 RETURN(0);
4284
4285         rc = osd_remote_fid(env, osd, fid);
4286         if (rc <= 0)
4287                 RETURN(rc);
4288
4289         rc = 0;
4290
4291         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
4292                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
4293         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4294                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4295         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4296                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4297
4298         RETURN(rc);
4299 }
4300
4301 /**
4302  * Index add function for interoperability mode (b11826).
4303  * It will add the directory entry.This entry is needed to
4304  * maintain name->fid mapping.
4305  *
4306  * \param key it is key i.e. file entry to be inserted
4307  * \param rec it is value of given key i.e. fid
4308  *
4309  * \retval   0, on success
4310  * \retval -ve, on error
4311  */
4312 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
4313                                const struct dt_rec *rec,
4314                                const struct dt_key *key, struct thandle *th,
4315                                struct lustre_capa *capa, int ignore_quota)
4316 {
4317         struct osd_object       *obj = osd_dt_obj(dt);
4318         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
4319         struct lu_fid           *fid = (struct lu_fid *) rec;
4320         const char              *name = (const char *)key;
4321         struct osd_thread_info  *oti   = osd_oti_get(env);
4322         struct osd_inode_id     *id    = &oti->oti_id;
4323         struct inode            *child_inode = NULL;
4324         struct osd_object       *child = NULL;
4325         int                     rc;
4326         ENTRY;
4327
4328         LASSERT(osd_invariant(obj));
4329         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4330         LASSERT(th != NULL);
4331
4332         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4333
4334         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
4335                 RETURN(-EACCES);
4336
4337         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!", PFID(fid));
4338
4339         rc = osd_remote_fid(env, osd, fid);
4340         if (rc < 0) {
4341                 CERROR("%s: Can not find object "DFID" rc %d\n",
4342                        osd_name(osd), PFID(fid), rc);
4343                 RETURN(rc);
4344         }
4345
4346         if (rc == 1) {
4347                 /* Insert remote entry */
4348                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
4349                         struct osd_mdobj_map    *omm = osd->od_mdt_map;
4350                         struct osd_thandle      *oh;
4351
4352                         /* If parent on remote MDT, we need put this object
4353                          * under AGENT */
4354                         oh = container_of(th, typeof(*oh), ot_super);
4355                         rc = osd_add_to_remote_parent(env, osd, obj, oh);
4356                         if (rc != 0) {
4357                                 CERROR("%s: add "DFID" error: rc = %d\n",
4358                                        osd_name(osd),
4359                                        PFID(lu_object_fid(&dt->do_lu)), rc);
4360                                 RETURN(rc);
4361                         }
4362
4363                         child_inode = igrab(omm->omm_remote_parent->d_inode);
4364                 } else {
4365                         child_inode = osd_create_local_agent_inode(env, osd,
4366                                                                    obj, fid,
4367                                                                    th);
4368                         if (IS_ERR(child_inode))
4369                                 RETURN(PTR_ERR(child_inode));
4370                 }
4371         } else {
4372                 /* Insert local entry */
4373                 child = osd_object_find(env, dt, fid);
4374                 if (IS_ERR(child)) {
4375                         CERROR("%s: Can not find object "DFID"%u:%u: rc = %d\n",
4376                                osd_name(osd), PFID(fid),
4377                                id->oii_ino, id->oii_gen,
4378                                (int)PTR_ERR(child));
4379                         RETURN(PTR_ERR(child));
4380                 }
4381                 child_inode = igrab(child->oo_inode);
4382         }
4383
4384         rc = osd_ea_add_rec(env, obj, child_inode, name, rec, th);
4385
4386         iput(child_inode);
4387         if (child != NULL)
4388                 osd_object_put(env, child);
4389         LASSERT(osd_invariant(obj));
4390         RETURN(rc);
4391 }
4392
4393 /**
4394  *  Initialize osd Iterator for given osd index object.
4395  *
4396  *  \param  dt      osd index object
4397  */
4398
4399 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
4400                                      struct dt_object *dt,
4401                                      __u32 unused,
4402                                      struct lustre_capa *capa)
4403 {
4404         struct osd_it_iam      *it;
4405         struct osd_thread_info *oti = osd_oti_get(env);
4406         struct osd_object      *obj = osd_dt_obj(dt);
4407         struct lu_object       *lo  = &dt->do_lu;
4408         struct iam_path_descr  *ipd;
4409         struct iam_container   *bag = &obj->oo_dir->od_container;
4410
4411         LASSERT(lu_object_exists(lo));
4412
4413         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
4414                 return ERR_PTR(-EACCES);
4415
4416         it = &oti->oti_it;
4417         ipd = osd_it_ipd_get(env, bag);
4418         if (likely(ipd != NULL)) {
4419                 it->oi_obj = obj;
4420                 it->oi_ipd = ipd;
4421                 lu_object_get(lo);
4422                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
4423                 return (struct dt_it *)it;
4424         }
4425         return ERR_PTR(-ENOMEM);
4426 }
4427
4428 /**
4429  * free given Iterator.
4430  */
4431
4432 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
4433 {
4434         struct osd_it_iam *it = (struct osd_it_iam *)di;
4435         struct osd_object *obj = it->oi_obj;
4436
4437         iam_it_fini(&it->oi_it);
4438         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
4439         lu_object_put(env, &obj->oo_dt.do_lu);
4440 }
4441
4442 /**
4443  *  Move Iterator to record specified by \a key
4444  *
4445  *  \param  di      osd iterator
4446  *  \param  key     key for index
4447  *
4448  *  \retval +ve  di points to record with least key not larger than key
4449  *  \retval  0   di points to exact matched key
4450  *  \retval -ve  failure
4451  */
4452
4453 static int osd_it_iam_get(const struct lu_env *env,
4454                           struct dt_it *di, const struct dt_key *key)
4455 {
4456         struct osd_thread_info  *oti = osd_oti_get(env);
4457         struct osd_it_iam       *it = (struct osd_it_iam *)di;
4458
4459         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4460                 /* swab quota uid/gid */
4461                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4462                 key = (struct dt_key *)&oti->oti_quota_id;
4463         }
4464
4465         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
4466 }
4467
4468 /**
4469  *  Release Iterator
4470  *
4471  *  \param  di      osd iterator
4472  */
4473 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
4474 {
4475         struct osd_it_iam *it = (struct osd_it_iam *)di;
4476
4477         iam_it_put(&it->oi_it);
4478 }
4479
4480 /**
4481  *  Move iterator by one record
4482  *
4483  *  \param  di      osd iterator
4484  *
4485  *  \retval +1   end of container reached
4486  *  \retval  0   success
4487  *  \retval -ve  failure
4488  */
4489
4490 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
4491 {
4492         struct osd_it_iam *it = (struct osd_it_iam *)di;
4493
4494         return iam_it_next(&it->oi_it);
4495 }
4496
4497 /**
4498  * Return pointer to the key under iterator.
4499  */
4500
4501 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
4502                                  const struct dt_it *di)
4503 {
4504         struct osd_thread_info *oti = osd_oti_get(env);
4505         struct osd_it_iam      *it = (struct osd_it_iam *)di;
4506         struct osd_object      *obj = it->oi_obj;
4507         struct dt_key          *key;
4508
4509         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
4510
4511         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
4512                 /* swab quota uid/gid */
4513                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
4514                 key = (struct dt_key *)&oti->oti_quota_id;
4515         }
4516
4517         return key;
4518 }
4519
4520 /**
4521  * Return size of key under iterator (in bytes)
4522  */
4523
4524 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
4525 {
4526         struct osd_it_iam *it = (struct osd_it_iam *)di;
4527
4528         return iam_it_key_size(&it->oi_it);
4529 }
4530
4531 static inline void
4532 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
4533 {
4534         /* check if file type is required */
4535         if (ent->lde_attrs & LUDA_TYPE) {
4536                 struct luda_type *lt;
4537                 int align = sizeof(*lt) - 1;
4538
4539                 len = (len + align) & ~align;
4540                 lt = (struct luda_type *)(ent->lde_name + len);
4541                 lt->lt_type = cpu_to_le16(DTTOIF(type));
4542         }
4543
4544         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
4545 }
4546
4547 /**
4548  * build lu direct from backend fs dirent.
4549  */
4550
4551 static inline void
4552 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
4553                    char *name, __u16 namelen, __u16 type, __u32 attr)
4554 {
4555         ent->lde_attrs = attr | LUDA_FID;
4556         fid_cpu_to_le(&ent->lde_fid, fid);
4557
4558         ent->lde_hash = cpu_to_le64(offset);
4559         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
4560
4561         strncpy(ent->lde_name, name, namelen);
4562         ent->lde_name[namelen] = '\0';
4563         ent->lde_namelen = cpu_to_le16(namelen);
4564
4565         /* append lustre attributes */
4566         osd_it_append_attrs(ent, namelen, type);
4567 }
4568
4569 /**
4570  * Return pointer to the record under iterator.
4571  */
4572 static int osd_it_iam_rec(const struct lu_env *env,
4573                           const struct dt_it *di,
4574                           struct dt_rec *dtrec, __u32 attr)
4575 {
4576         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
4577         struct osd_thread_info *info = osd_oti_get(env);
4578         ENTRY;
4579
4580         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
4581                 const struct osd_fid_pack *rec;
4582                 struct lu_fid             *fid = &info->oti_fid;
4583                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
4584                 char                      *name;
4585                 int                        namelen;
4586                 __u64                      hash;
4587                 int                        rc;
4588
4589                 name = (char *)iam_it_key_get(&it->oi_it);
4590                 if (IS_ERR(name))
4591                         RETURN(PTR_ERR(name));
4592
4593                 namelen = iam_it_key_size(&it->oi_it);
4594
4595                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
4596                 if (IS_ERR(rec))
4597                         RETURN(PTR_ERR(rec));
4598
4599                 rc = osd_fid_unpack(fid, rec);
4600                 if (rc)
4601                         RETURN(rc);
4602
4603                 hash = iam_it_store(&it->oi_it);
4604
4605                 /* IAM does not store object type in IAM index (dir) */
4606                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
4607                                    0, LUDA_FID);
4608         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4609                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4610                            (struct iam_rec *)dtrec);
4611                 osd_quota_unpack(it->oi_obj, dtrec);
4612         } else {
4613                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4614                            (struct iam_rec *)dtrec);
4615         }
4616
4617         RETURN(0);
4618 }
4619
4620 /**
4621  * Returns cookie for current Iterator position.
4622  */
4623 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
4624 {
4625         struct osd_it_iam *it = (struct osd_it_iam *)di;
4626
4627         return iam_it_store(&it->oi_it);
4628 }
4629
4630 /**
4631  * Restore iterator from cookie.
4632  *
4633  * \param  di      osd iterator
4634  * \param  hash    Iterator location cookie
4635  *
4636  * \retval +ve  di points to record with least key not larger than key.
4637  * \retval  0   di points to exact matched key
4638  * \retval -ve  failure
4639  */
4640
4641 static int osd_it_iam_load(const struct lu_env *env,
4642                            const struct dt_it *di, __u64 hash)
4643 {
4644         struct osd_it_iam *it = (struct osd_it_iam *)di;
4645
4646         return iam_it_load(&it->oi_it, hash);
4647 }
4648
4649 static const struct dt_index_operations osd_index_iam_ops = {
4650         .dio_lookup         = osd_index_iam_lookup,
4651         .dio_declare_insert = osd_index_declare_iam_insert,
4652         .dio_insert         = osd_index_iam_insert,
4653         .dio_declare_delete = osd_index_declare_iam_delete,
4654         .dio_delete         = osd_index_iam_delete,
4655         .dio_it     = {
4656                 .init     = osd_it_iam_init,
4657                 .fini     = osd_it_iam_fini,
4658                 .get      = osd_it_iam_get,
4659                 .put      = osd_it_iam_put,
4660                 .next     = osd_it_iam_next,
4661                 .key      = osd_it_iam_key,
4662                 .key_size = osd_it_iam_key_size,
4663                 .rec      = osd_it_iam_rec,
4664                 .store    = osd_it_iam_store,
4665                 .load     = osd_it_iam_load
4666         }
4667 };
4668
4669
4670 /**
4671  * Creates or initializes iterator context.
4672  *
4673  * \retval struct osd_it_ea, iterator structure on success
4674  *
4675  */
4676 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
4677                                     struct dt_object *dt,
4678                                     __u32 attr,
4679                                     struct lustre_capa *capa)
4680 {
4681         struct osd_object       *obj  = osd_dt_obj(dt);
4682         struct osd_thread_info  *info = osd_oti_get(env);
4683         struct osd_it_ea        *it   = &info->oti_it_ea;
4684         struct file             *file = &it->oie_file;
4685         struct lu_object        *lo   = &dt->do_lu;
4686         struct dentry           *obj_dentry = &info->oti_it_dentry;
4687         ENTRY;
4688         LASSERT(lu_object_exists(lo));
4689
4690         obj_dentry->d_inode = obj->oo_inode;
4691         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
4692         obj_dentry->d_name.hash = 0;
4693
4694         it->oie_rd_dirent       = 0;
4695         it->oie_it_dirent       = 0;
4696         it->oie_dirent          = NULL;
4697         it->oie_buf             = info->oti_it_ea_buf;
4698         it->oie_obj             = obj;
4699
4700         /* Reset the "file" totally to avoid to reuse any old value from
4701          * former readdir handling, the "file->f_pos" should be zero. */
4702         memset(file, 0, sizeof(*file));
4703         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
4704         if (attr & LUDA_64BITHASH)
4705                 file->f_mode    = FMODE_64BITHASH;
4706         else
4707                 file->f_mode    = FMODE_32BITHASH;
4708         file->f_dentry          = obj_dentry;
4709         file->f_mapping         = obj->oo_inode->i_mapping;
4710         file->f_op              = obj->oo_inode->i_fop;
4711         set_file_inode(file, obj->oo_inode);
4712
4713         lu_object_get(lo);
4714         RETURN((struct dt_it *) it);
4715 }
4716
4717 /**
4718  * Destroy or finishes iterator context.
4719  *
4720  * \param di iterator structure to be destroyed
4721  */
4722 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
4723 {
4724         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4725         struct osd_object    *obj  = it->oie_obj;
4726         struct inode       *inode  = obj->oo_inode;
4727
4728         ENTRY;
4729         it->oie_file.f_op->release(inode, &it->oie_file);
4730         lu_object_put(env, &obj->oo_dt.do_lu);
4731         EXIT;
4732 }
4733
4734 /**
4735  * It position the iterator at given key, so that next lookup continues from
4736  * that key Or it is similar to dio_it->load() but based on a key,
4737  * rather than file position.
4738  *
4739  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
4740  * to the beginning.
4741  *
4742  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
4743  */
4744 static int osd_it_ea_get(const struct lu_env *env,
4745                          struct dt_it *di, const struct dt_key *key)
4746 {
4747         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4748
4749         ENTRY;
4750         LASSERT(((const char *)key)[0] == '\0');
4751         it->oie_file.f_pos      = 0;
4752         it->oie_rd_dirent       = 0;
4753         it->oie_it_dirent       = 0;
4754         it->oie_dirent          = NULL;
4755
4756         RETURN(+1);
4757 }
4758
4759 /**
4760  * Does nothing
4761  */
4762 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
4763 {
4764 }
4765
4766 struct osd_filldir_cbs {
4767 #ifdef HAVE_DIR_CONTEXT
4768         struct dir_context ctx;
4769 #endif
4770         struct osd_it_ea  *it;
4771 };
4772 /**
4773  * It is called internally by ->readdir(). It fills the
4774  * iterator's in-memory data structure with required
4775  * information i.e. name, namelen, rec_size etc.
4776  *
4777  * \param buf in which information to be filled in.
4778  * \param name name of the file in given dir
4779  *
4780  * \retval 0 on success
4781  * \retval 1 on buffer full
4782  */
4783 static int osd_ldiskfs_filldir(void *buf, const char *name, int namelen,
4784                                loff_t offset, __u64 ino,
4785                                unsigned d_type)
4786 {
4787         struct osd_it_ea        *it   = ((struct osd_filldir_cbs *)buf)->it;
4788         struct osd_object       *obj  = it->oie_obj;
4789         struct osd_it_ea_dirent *ent  = it->oie_dirent;
4790         struct lu_fid           *fid  = &ent->oied_fid;
4791         struct osd_fid_pack     *rec;
4792         ENTRY;
4793
4794         /* this should never happen */
4795         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
4796                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
4797                 RETURN(-EIO);
4798         }
4799
4800         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
4801             OSD_IT_EA_BUFSIZE)
4802                 RETURN(1);
4803
4804         /* "." is just the object itself. */
4805         if (namelen == 1 && name[0] == '.') {
4806                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4807         } else if (d_type & LDISKFS_DIRENT_LUFID) {
4808                 rec = (struct osd_fid_pack*) (name + namelen + 1);
4809                 if (osd_fid_unpack(fid, rec) != 0)
4810                         fid_zero(fid);
4811         } else {
4812                 fid_zero(fid);
4813         }
4814         d_type &= ~LDISKFS_DIRENT_LUFID;
4815
4816         /* NOT export local root. */
4817         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
4818                 ino = obj->oo_inode->i_ino;
4819                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4820         }
4821
4822         ent->oied_ino     = ino;
4823         ent->oied_off     = offset;
4824         ent->oied_namelen = namelen;
4825         ent->oied_type    = d_type;
4826
4827         memcpy(ent->oied_name, name, namelen);
4828
4829         it->oie_rd_dirent++;
4830         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
4831         RETURN(0);
4832 }
4833
4834 /**
4835  * Calls ->readdir() to load a directory entry at a time
4836  * and stored it in iterator's in-memory data structure.
4837  *
4838  * \param di iterator's in memory structure
4839  *
4840  * \retval   0 on success
4841  * \retval -ve on error
4842  */
4843 static int osd_ldiskfs_it_fill(const struct lu_env *env,
4844                                const struct dt_it *di)
4845 {
4846         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
4847         struct osd_object  *obj   = it->oie_obj;
4848         struct inode       *inode = obj->oo_inode;
4849         struct htree_lock  *hlock = NULL;
4850         struct file        *filp  = &it->oie_file;
4851         int                 rc = 0;
4852         struct osd_filldir_cbs buf = {
4853 #ifdef HAVE_DIR_CONTEXT
4854                 .ctx.actor = osd_ldiskfs_filldir,
4855 #endif
4856                 .it = it
4857         };
4858
4859         ENTRY;
4860         it->oie_dirent = it->oie_buf;
4861         it->oie_rd_dirent = 0;
4862
4863         if (obj->oo_hl_head != NULL) {
4864                 hlock = osd_oti_get(env)->oti_hlock;
4865                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4866                                    inode, LDISKFS_HLOCK_READDIR);
4867         } else {
4868                 down_read(&obj->oo_ext_idx_sem);
4869         }
4870
4871 #ifdef HAVE_DIR_CONTEXT
4872         buf.ctx.pos = filp->f_pos;
4873         rc = inode->i_fop->iterate(filp, &buf.ctx);
4874         filp->f_pos = buf.ctx.pos;
4875 #else
4876         rc = inode->i_fop->readdir(filp, &buf, osd_ldiskfs_filldir);
4877 #endif
4878
4879         if (hlock != NULL)
4880                 ldiskfs_htree_unlock(hlock);
4881         else
4882                 up_read(&obj->oo_ext_idx_sem);
4883
4884         if (it->oie_rd_dirent == 0) {
4885                 /*If it does not get any dirent, it means it has been reached
4886                  *to the end of the dir */
4887                 it->oie_file.f_pos = ldiskfs_get_htree_eof(&it->oie_file);
4888         } else {
4889                 it->oie_dirent = it->oie_buf;
4890                 it->oie_it_dirent = 1;
4891         }
4892
4893         RETURN(rc);
4894 }
4895
4896 /**
4897  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4898  * to load a directory entry at a time and stored it in
4899  * iterator's in-memory data structure.
4900  *
4901  * \param di iterator's in memory structure
4902  *
4903  * \retval +ve iterator reached to end
4904  * \retval   0 iterator not reached to end
4905  * \retval -ve on error
4906  */
4907 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
4908 {
4909         struct osd_it_ea *it = (struct osd_it_ea *)di;
4910         int rc;
4911
4912         ENTRY;
4913
4914         if (it->oie_it_dirent < it->oie_rd_dirent) {
4915                 it->oie_dirent =
4916                         (void *) it->oie_dirent +
4917                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
4918                                        it->oie_dirent->oied_namelen);
4919                 it->oie_it_dirent++;
4920                 RETURN(0);
4921         } else {
4922                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
4923                         rc = +1;
4924                 else
4925                         rc = osd_ldiskfs_it_fill(env, di);
4926         }
4927
4928         RETURN(rc);
4929 }
4930
4931 /**
4932  * Returns the key at current position from iterator's in memory structure.
4933  *
4934  * \param di iterator's in memory structure
4935  *
4936  * \retval key i.e. struct dt_key on success
4937  */
4938 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
4939                                     const struct dt_it *di)
4940 {
4941         struct osd_it_ea *it = (struct osd_it_ea *)di;
4942
4943         return (struct dt_key *)it->oie_dirent->oied_name;
4944 }
4945
4946 /**
4947  * Returns the key's size at current position from iterator's in memory structure.
4948  *
4949  * \param di iterator's in memory structure
4950  *
4951  * \retval key_size i.e. struct dt_key on success
4952  */
4953 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
4954 {
4955         struct osd_it_ea *it = (struct osd_it_ea *)di;
4956
4957         return it->oie_dirent->oied_namelen;
4958 }
4959
4960 static int
4961 osd_dirent_update(handle_t *jh, struct super_block *sb,
4962                   struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4963                   struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de)
4964 {
4965         struct osd_fid_pack *rec;
4966         int                  rc;
4967         ENTRY;
4968
4969         LASSERT(de->file_type & LDISKFS_DIRENT_LUFID);
4970         LASSERT(de->rec_len >= de->name_len + sizeof(struct osd_fid_pack));
4971
4972         rc = ldiskfs_journal_get_write_access(jh, bh);
4973         if (rc != 0) {
4974                 CERROR("%.16s: fail to write access for update dirent: "
4975                        "name = %.*s, rc = %d\n",
4976                        LDISKFS_SB(sb)->s_es->s_volume_name,
4977                        ent->oied_namelen, ent->oied_name, rc);
4978                 RETURN(rc);
4979         }
4980
4981         rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4982         fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4983         rc = ldiskfs_journal_dirty_metadata(jh, bh);
4984         if (rc != 0)
4985                 CERROR("%.16s: fail to dirty metadata for update dirent: "
4986                        "name = %.*s, rc = %d\n",
4987                        LDISKFS_SB(sb)->s_es->s_volume_name,
4988                        ent->oied_namelen, ent->oied_name, rc);
4989
4990         RETURN(rc);
4991 }
4992
4993 static inline int
4994 osd_dirent_has_space(__u16 reclen, __u16 namelen, unsigned blocksize)
4995 {
4996         if (ldiskfs_rec_len_from_disk(reclen, blocksize) >=
4997             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
4998                 return 1;
4999         else
5000                 return 0;
5001 }
5002
5003 static inline int
5004 osd_dot_dotdot_has_space(struct ldiskfs_dir_entry_2 *de, int dot_dotdot)
5005 {
5006         LASSERTF(dot_dotdot == 1 || dot_dotdot == 2,
5007                  "dot_dotdot = %d\n", dot_dotdot);
5008
5009         if (LDISKFS_DIR_REC_LEN(de) >=
5010             __LDISKFS_DIR_REC_LEN(dot_dotdot + 1 + sizeof(struct osd_fid_pack)))
5011                 return 1;
5012         else
5013                 return 0;
5014 }
5015
5016 static int
5017 osd_dirent_reinsert(const struct lu_env *env, handle_t *jh,
5018                     struct inode *dir, struct inode *inode,
5019                     struct osd_it_ea_dirent *ent, struct lu_fid *fid,
5020                     struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de,
5021                     struct htree_lock *hlock)
5022 {
5023         struct dentry               *dentry;
5024         struct osd_fid_pack         *rec;
5025         struct ldiskfs_dentry_param *ldp;
5026         int                          rc;
5027         ENTRY;
5028
5029         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
5030                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
5031                 RETURN(0);
5032
5033         /* There is enough space to hold the FID-in-dirent. */
5034         if (osd_dirent_has_space(de->rec_len, ent->oied_namelen,
5035                                  dir->i_sb->s_blocksize)) {
5036                 rc = ldiskfs_journal_get_write_access(jh, bh);
5037                 if (rc != 0) {
5038                         CERROR("%.16s: fail to write access for reinsert "
5039                                "dirent: name = %.*s, rc = %d\n",
5040                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5041                                ent->oied_namelen, ent->oied_name, rc);
5042                         RETURN(rc);
5043                 }
5044
5045                 de->name[de->name_len] = 0;
5046                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
5047                 rec->fp_len = sizeof(struct lu_fid) + 1;
5048                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
5049                 de->file_type |= LDISKFS_DIRENT_LUFID;
5050
5051                 rc = ldiskfs_journal_dirty_metadata(jh, bh);
5052                 if (rc != 0)
5053                         CERROR("%.16s: fail to dirty metadata for reinsert "
5054                                "dirent: name = %.*s, rc = %d\n",
5055                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5056                                ent->oied_namelen, ent->oied_name, rc);
5057
5058                 RETURN(rc);
5059         }
5060
5061         rc = ldiskfs_delete_entry(jh, dir, de, bh);
5062         if (rc != 0) {
5063                 CERROR("%.16s: fail to delete entry for reinsert dirent: "
5064                        "name = %.*s, rc = %d\n",
5065                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5066                        ent->oied_namelen, ent->oied_name, rc);
5067                 RETURN(rc);
5068         }
5069
5070         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
5071                                            ent->oied_namelen);
5072         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
5073         osd_get_ldiskfs_dirent_param(ldp, (const struct dt_rec *)fid);
5074         dentry->d_fsdata = (void *)ldp;
5075         ll_vfs_dq_init(dir);
5076         rc = osd_ldiskfs_add_entry(jh, dentry, inode, hlock);
5077         /* It is too bad, we cannot reinsert the name entry back.
5078          * That means we lose it! */
5079         if (rc != 0)
5080                 CERROR("%.16s: fail to insert entry for reinsert dirent: "
5081                        "name = %.*s, rc = %d\n",
5082                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5083                        ent->oied_namelen, ent->oied_name, rc);
5084
5085         RETURN(rc);
5086 }
5087
5088 static int
5089 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
5090                         struct osd_it_ea *it, struct lu_fid *fid,
5091                         struct osd_inode_id *id, __u32 *attr)
5092 {
5093         struct osd_thread_info     *info        = osd_oti_get(env);
5094         struct lustre_mdt_attrs    *lma         = &info->oti_mdt_attrs;
5095         struct osd_device          *dev         = osd_obj2dev(obj);
5096         struct super_block         *sb          = osd_sb(dev);
5097         const char                 *devname     =
5098                                         LDISKFS_SB(sb)->s_es->s_volume_name;
5099         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
5100         struct inode               *dir         = obj->oo_inode;
5101         struct htree_lock          *hlock       = NULL;
5102         struct buffer_head         *bh          = NULL;
5103         handle_t                   *jh          = NULL;
5104         struct ldiskfs_dir_entry_2 *de;
5105         struct dentry              *dentry;
5106         struct inode               *inode;
5107         int                         credits;
5108         int                         rc;
5109         int                         dot_dotdot  = 0;
5110         bool                        dirty       = false;
5111         ENTRY;
5112
5113         if (ent->oied_name[0] == '.') {
5114                 if (ent->oied_namelen == 1)
5115                         dot_dotdot = 1;
5116                 else if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
5117                         dot_dotdot = 2;
5118         }
5119
5120         dentry = osd_child_dentry_get(env, obj, ent->oied_name,
5121                                       ent->oied_namelen);
5122
5123         /* We need to ensure that the name entry is still valid.
5124          * Because it may be removed or renamed by other already.
5125          *
5126          * The unlink or rename operation will start journal before PDO lock,
5127          * so to avoid deadlock, here we need to start journal handle before
5128          * related PDO lock also. But because we do not know whether there
5129          * will be something to be repaired before PDO lock, we just start
5130          * journal without conditions.
5131          *
5132          * We may need to remove the name entry firstly, then insert back.
5133          * One credit is for user quota file update.
5134          * One credit is for group quota file update.
5135          * Two credits are for dirty inode. */
5136         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
5137                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
5138
5139 again:
5140         if (dev->od_dirent_journal) {
5141                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
5142                 if (IS_ERR(jh)) {
5143                         rc = PTR_ERR(jh);
5144                         CERROR("%.16s: fail to start trans for dirent "
5145                                "check_repair: credits %d, name %.*s, rc %d\n",
5146                                devname, credits, ent->oied_namelen,
5147                                ent->oied_name, rc);
5148                         RETURN(rc);
5149                 }
5150
5151                 if (obj->oo_hl_head != NULL) {
5152                         hlock = osd_oti_get(env)->oti_hlock;
5153                         /* "0" means exclusive lock for the whole directory.
5154                          * We need to prevent others access such name entry
5155                          * during the delete + insert. Neither HLOCK_ADD nor
5156                          * HLOCK_DEL cannot guarantee the atomicity. */
5157                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
5158                 } else {
5159                         down_write(&obj->oo_ext_idx_sem);
5160                 }
5161         } else {
5162                 if (obj->oo_hl_head != NULL) {
5163                         hlock = osd_oti_get(env)->oti_hlock;
5164                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
5165                                            LDISKFS_HLOCK_LOOKUP);
5166                 } else {
5167                         down_read(&obj->oo_ext_idx_sem);
5168                 }
5169         }
5170
5171         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5172         /* For dot/dotdot entry, if there is not enough space to hold the
5173          * FID-in-dirent, just keep them there. It only happens when the
5174          * device upgraded from 1.8 or restored from MDT file-level backup.
5175          * For the whole directory, only dot/dotdot entry have no FID-in-dirent
5176          * and needs to get FID from LMA when readdir, it will not affect the
5177          * performance much. */
5178         if ((bh == NULL) || (le32_to_cpu(de->inode) != ent->oied_ino) ||
5179             (dot_dotdot != 0 && !osd_dot_dotdot_has_space(de, dot_dotdot))) {
5180                 *attr |= LUDA_IGNORE;
5181                 GOTO(out_journal, rc = 0);
5182         }
5183
5184         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
5185         inode = osd_iget(info, dev, id);
5186         if (IS_ERR(inode)) {
5187                 rc = PTR_ERR(inode);
5188                 if (rc == -ENOENT || rc == -ESTALE) {
5189                         *attr |= LUDA_IGNORE;
5190                         rc = 0;
5191                 }
5192
5193                 GOTO(out_journal, rc);
5194         }
5195
5196         /* skip the REMOTE_PARENT_DIR. */
5197         if (inode == dev->od_mdt_map->omm_remote_parent->d_inode)
5198                 GOTO(out_inode, rc = 0);
5199
5200         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
5201         if (rc == 0) {
5202                 LASSERT(!(lma->lma_compat & LMAC_NOT_IN_OI));
5203
5204                 if (fid_is_sane(fid)) {
5205                         /* FID-in-dirent is valid. */
5206                         if (lu_fid_eq(fid, &lma->lma_self_fid))
5207                                 GOTO(out_inode, rc = 0);
5208
5209                         /* Do not repair under dryrun mode. */
5210                         if (*attr & LUDA_VERIFY_DRYRUN) {
5211                                 *attr |= LUDA_REPAIR;
5212                                 GOTO(out_inode, rc = 0);
5213                         }
5214
5215                         if (!dev->od_dirent_journal) {
5216                                 iput(inode);
5217                                 brelse(bh);
5218                                 if (hlock != NULL)
5219                                         ldiskfs_htree_unlock(hlock);
5220                                 else
5221                                         up_read(&obj->oo_ext_idx_sem);
5222                                 dev->od_dirent_journal = 1;
5223                                 goto again;
5224                         }
5225
5226                         *fid = lma->lma_self_fid;
5227                         dirty = true;
5228                         /* Update the FID-in-dirent. */
5229                         rc = osd_dirent_update(jh, sb, ent, fid, bh, de);
5230                         if (rc == 0)
5231                                 *attr |= LUDA_REPAIR;
5232                 } else {
5233                         /* Do not repair under dryrun mode. */
5234                         if (*attr & LUDA_VERIFY_DRYRUN) {
5235                                 *fid = lma->lma_self_fid;
5236                                 *attr |= LUDA_REPAIR;
5237                                 GOTO(out_inode, rc = 0);
5238                         }
5239
5240                         if (!dev->od_dirent_journal) {
5241                                 iput(inode);
5242                                 brelse(bh);
5243                                 if (hlock != NULL)
5244                                         ldiskfs_htree_unlock(hlock);
5245                                 else
5246                                         up_read(&obj->oo_ext_idx_sem);
5247                                 dev->od_dirent_journal = 1;
5248                                 goto again;
5249                         }
5250
5251                         *fid = lma->lma_self_fid;
5252                         dirty = true;
5253                         /* Append the FID-in-dirent. */
5254                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5255                                                  fid, bh, de, hlock);
5256                         if (rc == 0)
5257                                 *attr |= LUDA_REPAIR;
5258                 }
5259         } else if (rc == -ENODATA) {
5260                 /* Do not repair under dryrun mode. */
5261                 if (*attr & LUDA_VERIFY_DRYRUN) {
5262                         if (fid_is_sane(fid)) {
5263                                 *attr |= LUDA_REPAIR;
5264                         } else {
5265                                 lu_igif_build(fid, inode->i_ino,
5266                                               inode->i_generation);
5267                                 *attr |= LUDA_UPGRADE;
5268                         }
5269                         GOTO(out_inode, rc = 0);
5270                 }
5271
5272                 if (!dev->od_dirent_journal) {
5273                         iput(inode);
5274                         brelse(bh);
5275                         if (hlock != NULL)
5276                                 ldiskfs_htree_unlock(hlock);
5277                         else
5278                                 up_read(&obj->oo_ext_idx_sem);
5279                         dev->od_dirent_journal = 1;
5280                         goto again;
5281                 }
5282
5283                 dirty = true;
5284                 if (unlikely(fid_is_sane(fid))) {
5285                         /* FID-in-dirent exists, but FID-in-LMA is lost.
5286                          * Trust the FID-in-dirent, and add FID-in-LMA. */
5287                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
5288                         if (rc == 0)
5289                                 *attr |= LUDA_REPAIR;
5290                 } else {
5291                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
5292                         /* It is probably IGIF object. Only aappend the
5293                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
5294                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5295                                                  fid, bh, de, hlock);
5296                         if (rc == 0)
5297                                 *attr |= LUDA_UPGRADE;
5298                 }
5299         }
5300
5301         GOTO(out_inode, rc);
5302
5303 out_inode:
5304         iput(inode);
5305
5306 out_journal:
5307         brelse(bh);
5308         if (hlock != NULL) {
5309                 ldiskfs_htree_unlock(hlock);
5310         } else {
5311                 if (dev->od_dirent_journal)
5312                         up_write(&obj->oo_ext_idx_sem);
5313                 else
5314                         up_read(&obj->oo_ext_idx_sem);
5315         }
5316         if (jh != NULL)
5317                 ldiskfs_journal_stop(jh);
5318         if (rc >= 0 && !dirty)
5319                 dev->od_dirent_journal = 0;
5320         return rc;
5321 }
5322
5323 /**
5324  * Returns the value at current position from iterator's in memory structure.
5325  *
5326  * \param di struct osd_it_ea, iterator's in memory structure
5327  * \param attr attr requested for dirent.
5328  * \param lde lustre dirent
5329  *
5330  * \retval   0 no error and \param lde has correct lustre dirent.
5331  * \retval -ve on error
5332  */
5333 static inline int osd_it_ea_rec(const struct lu_env *env,
5334                                 const struct dt_it *di,
5335                                 struct dt_rec *dtrec, __u32 attr)
5336 {
5337         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
5338         struct osd_object      *obj   = it->oie_obj;
5339         struct osd_device      *dev   = osd_obj2dev(obj);
5340         struct osd_scrub       *scrub = &dev->od_scrub;
5341         struct scrub_file      *sf    = &scrub->os_file;
5342         struct osd_thread_info *oti   = osd_oti_get(env);
5343         struct osd_inode_id    *id    = &oti->oti_id;
5344         struct osd_idmap_cache *oic   = &oti->oti_cache;
5345         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
5346         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
5347         __u32                   ino   = it->oie_dirent->oied_ino;
5348         int                     rc    = 0;
5349         ENTRY;
5350
5351         if (attr & LUDA_VERIFY) {
5352                 attr |= LUDA_TYPE;
5353                 if (unlikely(ino == osd_sb(dev)->s_root->d_inode->i_ino)) {
5354                         attr |= LUDA_IGNORE;
5355                         rc = 0;
5356                 } else {
5357                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
5358                                                      &attr);
5359                 }
5360         } else {
5361                 attr &= ~LU_DIRENT_ATTRS_MASK;
5362                 if (!fid_is_sane(fid)) {
5363                         if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
5364                                 RETURN(-ENOENT);
5365
5366                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
5367                 } else {
5368                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5369                 }
5370         }
5371
5372         /* Pack the entry anyway, at least the offset is right. */
5373         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
5374                            it->oie_dirent->oied_name,
5375                            it->oie_dirent->oied_namelen,
5376                            it->oie_dirent->oied_type, attr);
5377
5378         if (rc < 0)
5379                 RETURN(rc);
5380
5381         if (osd_remote_fid(env, dev, fid))
5382                 RETURN(0);
5383
5384         if (likely(!(attr & LUDA_IGNORE)))
5385                 rc = osd_add_oi_cache(oti, dev, id, fid);
5386
5387         if (!(attr & LUDA_VERIFY) &&
5388             (scrub->os_pos_current <= ino) &&
5389             ((sf->sf_flags & SF_INCONSISTENT) ||
5390              (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
5391              ldiskfs_test_bit(osd_oi_fid2idx(dev, fid), sf->sf_oi_bitmap)))
5392                 osd_consistency_check(oti, dev, oic);
5393
5394         RETURN(rc);
5395 }
5396
5397 /**
5398  * Returns a cookie for current position of the iterator head, so that
5399  * user can use this cookie to load/start the iterator next time.
5400  *
5401  * \param di iterator's in memory structure
5402  *
5403  * \retval cookie for current position, on success
5404  */
5405 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
5406 {
5407         struct osd_it_ea *it = (struct osd_it_ea *)di;
5408
5409         return it->oie_dirent->oied_off;
5410 }
5411
5412 /**
5413  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5414  * to load a directory entry at a time and stored it i inn,
5415  * in iterator's in-memory data structure.
5416  *
5417  * \param di struct osd_it_ea, iterator's in memory structure
5418  *
5419  * \retval +ve on success
5420  * \retval -ve on error
5421  */
5422 static int osd_it_ea_load(const struct lu_env *env,
5423                           const struct dt_it *di, __u64 hash)
5424 {
5425         struct osd_it_ea *it = (struct osd_it_ea *)di;
5426         int rc;
5427
5428         ENTRY;
5429         it->oie_file.f_pos = hash;
5430
5431         rc =  osd_ldiskfs_it_fill(env, di);
5432         if (rc == 0)
5433                 rc = +1;
5434
5435         RETURN(rc);
5436 }
5437
5438 /**
5439  * Index lookup function for interoperability mode (b11826).
5440  *
5441  * \param key,  key i.e. file name to be searched
5442  *
5443  * \retval +ve, on success
5444  * \retval -ve, on error
5445  */
5446 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
5447                                struct dt_rec *rec, const struct dt_key *key,
5448                                struct lustre_capa *capa)
5449 {
5450         struct osd_object *obj = osd_dt_obj(dt);
5451         int rc = 0;
5452
5453         ENTRY;
5454
5455         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
5456         LINVRNT(osd_invariant(obj));
5457
5458         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
5459                 return -EACCES;
5460
5461         rc = osd_ea_lookup_rec(env, obj, rec, key);
5462         if (rc == 0)
5463                 rc = +1;
5464         RETURN(rc);
5465 }
5466
5467 /**
5468  * Index and Iterator operations for interoperability
5469  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
5470  */
5471 static const struct dt_index_operations osd_index_ea_ops = {
5472         .dio_lookup         = osd_index_ea_lookup,
5473         .dio_declare_insert = osd_index_declare_ea_insert,
5474         .dio_insert         = osd_index_ea_insert,
5475         .dio_declare_delete = osd_index_declare_ea_delete,
5476         .dio_delete         = osd_index_ea_delete,
5477         .dio_it     = {
5478                 .init     = osd_it_ea_init,
5479                 .fini     = osd_it_ea_fini,
5480                 .get      = osd_it_ea_get,
5481                 .put      = osd_it_ea_put,
5482                 .next     = osd_it_ea_next,
5483                 .key      = osd_it_ea_key,
5484                 .key_size = osd_it_ea_key_size,
5485                 .rec      = osd_it_ea_rec,
5486                 .store    = osd_it_ea_store,
5487                 .load     = osd_it_ea_load
5488         }
5489 };
5490
5491 static void *osd_key_init(const struct lu_context *ctx,
5492                           struct lu_context_key *key)
5493 {
5494         struct osd_thread_info *info;
5495
5496         OBD_ALLOC_PTR(info);
5497         if (info == NULL)
5498                 return ERR_PTR(-ENOMEM);
5499
5500         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5501         if (info->oti_it_ea_buf == NULL)
5502                 goto out_free_info;
5503
5504         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
5505
5506         info->oti_hlock = ldiskfs_htree_lock_alloc();
5507         if (info->oti_hlock == NULL)
5508                 goto out_free_ea;
5509
5510         return info;
5511
5512  out_free_ea:
5513         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5514  out_free_info:
5515         OBD_FREE_PTR(info);
5516         return ERR_PTR(-ENOMEM);
5517 }
5518
5519 static void osd_key_fini(const struct lu_context *ctx,
5520                          struct lu_context_key *key, void* data)
5521 {
5522         struct osd_thread_info *info = data;
5523
5524         if (info->oti_hlock != NULL)
5525                 ldiskfs_htree_lock_free(info->oti_hlock);
5526         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5527         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
5528         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
5529         OBD_FREE_PTR(info);
5530 }
5531
5532 static void osd_key_exit(const struct lu_context *ctx,
5533                          struct lu_context_key *key, void *data)
5534 {
5535         struct osd_thread_info *info = data;
5536
5537         LASSERT(info->oti_r_locks == 0);
5538         LASSERT(info->oti_w_locks == 0);
5539         LASSERT(info->oti_txns    == 0);
5540 }
5541
5542 /* type constructor/destructor: osd_type_init, osd_type_fini */
5543 LU_TYPE_INIT_FINI(osd, &osd_key);
5544
5545 struct lu_context_key osd_key = {
5546         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
5547         .lct_init = osd_key_init,
5548         .lct_fini = osd_key_fini,
5549         .lct_exit = osd_key_exit
5550 };
5551
5552
5553 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
5554                            const char *name, struct lu_device *next)
5555 {
5556         struct osd_device *osd = osd_dev(d);
5557
5558         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
5559             >= sizeof(osd->od_svname))
5560                 return -E2BIG;
5561         return osd_procfs_init(osd, name);
5562 }
5563
5564 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
5565 {
5566         ENTRY;
5567
5568         /* shutdown quota slave instance associated with the device */
5569         if (o->od_quota_slave != NULL) {
5570                 qsd_fini(env, o->od_quota_slave);
5571                 o->od_quota_slave = NULL;
5572         }
5573
5574         RETURN(0);
5575 }
5576
5577 static void osd_umount(const struct lu_env *env, struct osd_device *o)
5578 {
5579         ENTRY;
5580
5581         if (o->od_mnt != NULL) {
5582                 shrink_dcache_sb(osd_sb(o));
5583                 osd_sync(env, &o->od_dt_dev);
5584
5585                 mntput(o->od_mnt);
5586                 o->od_mnt = NULL;
5587         }
5588
5589         EXIT;
5590 }
5591
5592 static int osd_mount(const struct lu_env *env,
5593                      struct osd_device *o, struct lustre_cfg *cfg)
5594 {
5595         const char              *name  = lustre_cfg_string(cfg, 0);
5596         const char              *dev  = lustre_cfg_string(cfg, 1);
5597         const char              *opts;
5598         unsigned long            page, s_flags, lmd_flags = 0;
5599         struct page             *__page;
5600         struct file_system_type *type;
5601         char                    *options = NULL;
5602         char                    *str;
5603         struct osd_thread_info  *info = osd_oti_get(env);
5604         struct lu_fid           *fid = &info->oti_fid;
5605         struct inode            *inode;
5606         int                      rc = 0;
5607         ENTRY;
5608
5609         if (o->od_mnt != NULL)
5610                 RETURN(0);
5611
5612         if (strlen(dev) >= sizeof(o->od_mntdev))
5613                 RETURN(-E2BIG);
5614         strcpy(o->od_mntdev, dev);
5615
5616         OBD_PAGE_ALLOC(__page, GFP_IOFS);
5617         if (__page == NULL)
5618                 GOTO(out, rc = -ENOMEM);
5619
5620         str = lustre_cfg_string(cfg, 2);
5621         s_flags = simple_strtoul(str, NULL, 0);
5622         str = strstr(str, ":");
5623         if (str)
5624                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
5625         opts = lustre_cfg_string(cfg, 3);
5626         page = (unsigned long)page_address(__page);
5627         options = (char *)page;
5628         *options = '\0';
5629         if (opts == NULL)
5630                 strcat(options, "user_xattr,acl");
5631         else
5632                 strcat(options, opts);
5633
5634         /* Glom up mount options */
5635         if (*options != '\0')
5636                 strcat(options, ",");
5637         strlcat(options, "no_mbcache", PAGE_CACHE_SIZE);
5638
5639         type = get_fs_type("ldiskfs");
5640         if (!type) {
5641                 CERROR("%s: cannot find ldiskfs module\n", name);
5642                 GOTO(out, rc = -ENODEV);
5643         }
5644
5645         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
5646         module_put(type->owner);
5647
5648         if (IS_ERR(o->od_mnt)) {
5649                 rc = PTR_ERR(o->od_mnt);
5650                 o->od_mnt = NULL;
5651                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
5652                 GOTO(out, rc);
5653         }
5654
5655 #ifdef HAVE_DEV_SET_RDONLY
5656         if (dev_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
5657                 CERROR("%s: underlying device %s is marked as read-only. "
5658                        "Setup failed\n", name, dev);
5659                 GOTO(out_mnt, rc = -EROFS);
5660         }
5661 #endif
5662
5663         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
5664                                         LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
5665                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
5666                 GOTO(out_mnt, rc = -EINVAL);
5667         }
5668
5669 #ifdef LDISKFS_MOUNT_DIRDATA
5670         if (LDISKFS_HAS_INCOMPAT_FEATURE(o->od_mnt->mnt_sb,
5671                                          LDISKFS_FEATURE_INCOMPAT_DIRDATA))
5672                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
5673 #endif
5674         inode = osd_sb(o)->s_root->d_inode;
5675         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
5676         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
5677         if (rc != 0) {
5678                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
5679                 GOTO(out_mnt, rc);
5680         }
5681
5682         if (lmd_flags & LMD_FLG_NOSCRUB)
5683                 o->od_noscrub = 1;
5684
5685         GOTO(out, rc = 0);
5686
5687 out_mnt:
5688         mntput(o->od_mnt);
5689         o->od_mnt = NULL;
5690
5691 out:
5692         if (__page)
5693                 OBD_PAGE_FREE(__page);
5694
5695         return rc;
5696 }
5697
5698 static struct lu_device *osd_device_fini(const struct lu_env *env,
5699                                          struct lu_device *d)
5700 {
5701         struct osd_device *o = osd_dev(d);
5702         ENTRY;
5703
5704         osd_shutdown(env, o);
5705         osd_procfs_fini(o);
5706         osd_scrub_cleanup(env, o);
5707         osd_obj_map_fini(o);
5708         osd_umount(env, o);
5709
5710         RETURN(NULL);
5711 }
5712
5713 static int osd_device_init0(const struct lu_env *env,
5714                             struct osd_device *o,
5715                             struct lustre_cfg *cfg)
5716 {
5717         struct lu_device        *l = osd2lu_dev(o);
5718         struct osd_thread_info *info;
5719         int                     rc;
5720         int                     cplen = 0;
5721
5722         /* if the module was re-loaded, env can loose its keys */
5723         rc = lu_env_refill((struct lu_env *) env);
5724         if (rc)
5725                 GOTO(out, rc);
5726         info = osd_oti_get(env);
5727         LASSERT(info);
5728
5729         l->ld_ops = &osd_lu_ops;
5730         o->od_dt_dev.dd_ops = &osd_dt_ops;
5731
5732         spin_lock_init(&o->od_osfs_lock);
5733         mutex_init(&o->od_otable_mutex);
5734
5735         o->od_capa_hash = init_capa_hash();
5736         if (o->od_capa_hash == NULL)
5737                 GOTO(out, rc = -ENOMEM);
5738
5739         o->od_read_cache = 1;
5740         o->od_writethrough_cache = 1;
5741         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
5742
5743         rc = osd_mount(env, o, cfg);
5744         if (rc)
5745                 GOTO(out_capa, rc);
5746
5747         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
5748                         sizeof(o->od_svname));
5749         if (cplen >= sizeof(o->od_svname)) {
5750                 rc = -E2BIG;
5751                 GOTO(out_mnt, rc);
5752         }
5753
5754         if (server_name_is_ost(o->od_svname))
5755                 o->od_is_ost = 1;
5756
5757         rc = osd_obj_map_init(env, o);
5758         if (rc != 0)
5759                 GOTO(out_mnt, rc);
5760
5761         rc = lu_site_init(&o->od_site, l);
5762         if (rc != 0)
5763                 GOTO(out_compat, rc);
5764         o->od_site.ls_bottom_dev = l;
5765
5766         rc = lu_site_init_finish(&o->od_site);
5767         if (rc != 0)
5768                 GOTO(out_site, rc);
5769
5770         /* self-repair LMA by default */
5771         o->od_lma_self_repair = 1;
5772
5773         CFS_INIT_LIST_HEAD(&o->od_ios_list);
5774         /* setup scrub, including OI files initialization */
5775         rc = osd_scrub_setup(env, o);
5776         if (rc < 0)
5777                 GOTO(out_site, rc);
5778
5779         rc = osd_procfs_init(o, o->od_svname);
5780         if (rc != 0) {
5781                 CERROR("%s: can't initialize procfs: rc = %d\n",
5782                        o->od_svname, rc);
5783                 GOTO(out_scrub, rc);
5784         }
5785
5786         LASSERT(l->ld_site->ls_linkage.next && l->ld_site->ls_linkage.prev);
5787
5788         /* initialize quota slave instance */
5789         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
5790                                      o->od_proc_entry);
5791         if (IS_ERR(o->od_quota_slave)) {
5792                 rc = PTR_ERR(o->od_quota_slave);
5793                 o->od_quota_slave = NULL;
5794                 GOTO(out_procfs, rc);
5795         }
5796
5797         RETURN(0);
5798
5799 out_procfs:
5800         osd_procfs_fini(o);
5801 out_scrub:
5802         osd_scrub_cleanup(env, o);
5803 out_site:
5804         lu_site_fini(&o->od_site);
5805 out_compat:
5806         osd_obj_map_fini(o);
5807 out_mnt:
5808         osd_umount(env, o);
5809 out_capa:
5810         cleanup_capa_hash(o->od_capa_hash);
5811 out:
5812         return rc;
5813 }
5814
5815 static struct lu_device *osd_device_alloc(const struct lu_env *env,
5816                                           struct lu_device_type *t,
5817                                           struct lustre_cfg *cfg)
5818 {
5819         struct osd_device *o;
5820         int                rc;
5821
5822         OBD_ALLOC_PTR(o);
5823         if (o == NULL)
5824                 return ERR_PTR(-ENOMEM);
5825
5826         rc = dt_device_init(&o->od_dt_dev, t);
5827         if (rc == 0) {
5828                 /* Because the ctx might be revived in dt_device_init,
5829                  * refill the env here */
5830                 lu_env_refill((struct lu_env *)env);
5831                 rc = osd_device_init0(env, o, cfg);
5832                 if (rc)
5833                         dt_device_fini(&o->od_dt_dev);
5834         }
5835
5836         if (unlikely(rc != 0))
5837                 OBD_FREE_PTR(o);
5838
5839         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
5840 }
5841
5842 static struct lu_device *osd_device_free(const struct lu_env *env,
5843                                          struct lu_device *d)
5844 {
5845         struct osd_device *o = osd_dev(d);
5846         ENTRY;
5847
5848         cleanup_capa_hash(o->od_capa_hash);
5849         /* XXX: make osd top device in order to release reference */
5850         d->ld_site->ls_top_dev = d;
5851         lu_site_purge(env, d->ld_site, -1);
5852         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
5853                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
5854                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
5855         }
5856         lu_site_fini(&o->od_site);
5857         dt_device_fini(&o->od_dt_dev);
5858         OBD_FREE_PTR(o);
5859         RETURN(NULL);
5860 }
5861
5862 static int osd_process_config(const struct lu_env *env,
5863                               struct lu_device *d, struct lustre_cfg *cfg)
5864 {
5865         struct osd_device               *o = osd_dev(d);
5866         int                             rc;
5867         ENTRY;
5868
5869         switch (cfg->lcfg_command) {
5870         case LCFG_SETUP:
5871                 rc = osd_mount(env, o, cfg);
5872                 break;
5873         case LCFG_CLEANUP:
5874                 lu_dev_del_linkage(d->ld_site, d);
5875                 rc = osd_shutdown(env, o);
5876                 break;
5877         case LCFG_PARAM:
5878                 LASSERT(&o->od_dt_dev);
5879                 rc = class_process_proc_param(PARAM_OSD, lprocfs_osd_obd_vars,
5880                                               cfg, &o->od_dt_dev);
5881                 if (rc > 0 || rc == -ENOSYS)
5882                         rc = class_process_proc_param(PARAM_OST,
5883                                                       lprocfs_osd_obd_vars,
5884                                                       cfg, &o->od_dt_dev);
5885                 break;
5886         default:
5887                 rc = -ENOSYS;
5888         }
5889
5890         RETURN(rc);
5891 }
5892
5893 static int osd_recovery_complete(const struct lu_env *env,
5894                                  struct lu_device *d)
5895 {
5896         struct osd_device       *osd = osd_dev(d);
5897         int                      rc = 0;
5898         ENTRY;
5899
5900         if (osd->od_quota_slave == NULL)
5901                 RETURN(0);
5902
5903         /* start qsd instance on recovery completion, this notifies the quota
5904          * slave code that we are about to process new requests now */
5905         rc = qsd_start(env, osd->od_quota_slave);
5906         RETURN(rc);
5907 }
5908
5909 /*
5910  * we use exports to track all osd users
5911  */
5912 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
5913                            struct obd_device *obd, struct obd_uuid *cluuid,
5914                            struct obd_connect_data *data, void *localdata)
5915 {
5916         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
5917         struct lustre_handle  conn;
5918         int                   rc;
5919         ENTRY;
5920
5921         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
5922
5923         rc = class_connect(&conn, obd, cluuid);
5924         if (rc)
5925                 RETURN(rc);
5926
5927         *exp = class_conn2export(&conn);
5928
5929         spin_lock(&osd->od_osfs_lock);
5930         osd->od_connects++;
5931         spin_unlock(&osd->od_osfs_lock);
5932
5933         RETURN(0);
5934 }
5935
5936 /*
5937  * once last export (we don't count self-export) disappeared
5938  * osd can be released
5939  */
5940 static int osd_obd_disconnect(struct obd_export *exp)
5941 {
5942         struct obd_device *obd = exp->exp_obd;
5943         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
5944         int                rc, release = 0;
5945         ENTRY;
5946
5947         /* Only disconnect the underlying layers on the final disconnect. */
5948         spin_lock(&osd->od_osfs_lock);
5949         osd->od_connects--;
5950         if (osd->od_connects == 0)
5951                 release = 1;
5952         spin_unlock(&osd->od_osfs_lock);
5953
5954         rc = class_disconnect(exp); /* bz 9811 */
5955
5956         if (rc == 0 && release)
5957                 class_manual_cleanup(obd);
5958         RETURN(rc);
5959 }
5960
5961 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
5962                        struct lu_device *dev)
5963 {
5964         struct osd_device *osd = osd_dev(dev);
5965         int                result = 0;
5966         ENTRY;
5967
5968         if (osd->od_quota_slave != NULL)
5969                 /* set up quota slave objects */
5970                 result = qsd_prepare(env, osd->od_quota_slave);
5971
5972         RETURN(result);
5973 }
5974
5975 static const struct lu_object_operations osd_lu_obj_ops = {
5976         .loo_object_init      = osd_object_init,
5977         .loo_object_delete    = osd_object_delete,
5978         .loo_object_release   = osd_object_release,
5979         .loo_object_free      = osd_object_free,
5980         .loo_object_print     = osd_object_print,
5981         .loo_object_invariant = osd_object_invariant
5982 };
5983
5984 const struct lu_device_operations osd_lu_ops = {
5985         .ldo_object_alloc      = osd_object_alloc,
5986         .ldo_process_config    = osd_process_config,
5987         .ldo_recovery_complete = osd_recovery_complete,
5988         .ldo_prepare           = osd_prepare,
5989 };
5990
5991 static const struct lu_device_type_operations osd_device_type_ops = {
5992         .ldto_init = osd_type_init,
5993         .ldto_fini = osd_type_fini,
5994
5995         .ldto_start = osd_type_start,
5996         .ldto_stop  = osd_type_stop,
5997
5998         .ldto_device_alloc = osd_device_alloc,
5999         .ldto_device_free  = osd_device_free,
6000
6001         .ldto_device_init    = osd_device_init,
6002         .ldto_device_fini    = osd_device_fini
6003 };
6004
6005 struct lu_device_type osd_device_type = {
6006         .ldt_tags     = LU_DEVICE_DT,
6007         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
6008         .ldt_ops      = &osd_device_type_ops,
6009         .ldt_ctx_tags = LCT_LOCAL,
6010 };
6011
6012 /*
6013  * lprocfs legacy support.
6014  */
6015 static struct obd_ops osd_obd_device_ops = {
6016         .o_owner = THIS_MODULE,
6017         .o_connect      = osd_obd_connect,
6018         .o_disconnect   = osd_obd_disconnect
6019 };
6020
6021 static int __init osd_mod_init(void)
6022 {
6023         int rc;
6024
6025         osd_oi_mod_init();
6026
6027         rc = lu_kmem_init(ldiskfs_caches);
6028         if (rc)
6029                 return rc;
6030
6031         rc = class_register_type(&osd_obd_device_ops, NULL, NULL,
6032 #ifndef HAVE_ONLY_PROCFS_SEQ
6033                                 lprocfs_osd_module_vars,
6034 #endif
6035                                 LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
6036         if (rc)
6037                 lu_kmem_fini(ldiskfs_caches);
6038         return rc;
6039 }
6040
6041 static void __exit osd_mod_exit(void)
6042 {
6043         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
6044         lu_kmem_fini(ldiskfs_caches);
6045 }
6046
6047 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
6048 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
6049 MODULE_LICENSE("GPL");
6050
6051 cfs_module(osd, "0.1.0", osd_mod_init, osd_mod_exit);