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