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