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