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