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