Whamcloud - gitweb
d5895566f5884676c6803018fa68a4528472001c
[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                                LA_TYPE;
1368
1369         attr->la_atime      = LTIME_S(inode->i_atime);
1370         attr->la_mtime      = LTIME_S(inode->i_mtime);
1371         attr->la_ctime      = LTIME_S(inode->i_ctime);
1372         attr->la_mode       = inode->i_mode;
1373         attr->la_size       = i_size_read(inode);
1374         attr->la_blocks     = inode->i_blocks;
1375         attr->la_uid        = inode->i_uid;
1376         attr->la_gid        = inode->i_gid;
1377         attr->la_flags      = LDISKFS_I(inode)->i_flags;
1378         attr->la_nlink      = inode->i_nlink;
1379         attr->la_rdev       = inode->i_rdev;
1380         attr->la_blksize    = 1 << inode->i_blkbits;
1381         attr->la_blkbits    = inode->i_blkbits;
1382 }
1383
1384 static int osd_attr_get(const struct lu_env *env,
1385                         struct dt_object *dt,
1386                         struct lu_attr *attr,
1387                         struct lustre_capa *capa)
1388 {
1389         struct osd_object *obj = osd_dt_obj(dt);
1390
1391         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1392         LINVRNT(osd_invariant(obj));
1393
1394         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
1395                 return -EACCES;
1396
1397         spin_lock(&obj->oo_guard);
1398         osd_inode_getattr(env, obj->oo_inode, attr);
1399         spin_unlock(&obj->oo_guard);
1400         return 0;
1401 }
1402
1403 static int osd_declare_attr_set(const struct lu_env *env,
1404                                 struct dt_object *dt,
1405                                 const struct lu_attr *attr,
1406                                 struct thandle *handle)
1407 {
1408         struct osd_thandle     *oh;
1409         struct osd_object      *obj;
1410         struct osd_thread_info *info = osd_oti_get(env);
1411         struct lquota_id_info  *qi = &info->oti_qi;
1412         long long               bspace;
1413         int                     rc = 0;
1414         bool                    allocated;
1415         ENTRY;
1416
1417         LASSERT(dt != NULL);
1418         LASSERT(handle != NULL);
1419
1420         obj = osd_dt_obj(dt);
1421         LASSERT(osd_invariant(obj));
1422
1423         oh = container_of0(handle, struct osd_thandle, ot_super);
1424         LASSERT(oh->ot_handle == NULL);
1425
1426         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
1427                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
1428
1429         if (attr == NULL || obj->oo_inode == NULL)
1430                 RETURN(rc);
1431
1432         bspace   = obj->oo_inode->i_blocks;
1433         bspace <<= obj->oo_inode->i_sb->s_blocksize_bits;
1434         bspace   = toqb(bspace);
1435
1436         /* Changing ownership is always preformed by super user, it should not
1437          * fail with EDQUOT.
1438          *
1439          * We still need to call the osd_declare_qid() to calculate the journal
1440          * credits for updating quota accounting files and to trigger quota
1441          * space adjustment once the operation is completed.*/
1442         if ((attr->la_valid & LA_UID) != 0 &&
1443              attr->la_uid != obj->oo_inode->i_uid) {
1444                 qi->lqi_type = USRQUOTA;
1445
1446                 /* inode accounting */
1447                 qi->lqi_is_blk = false;
1448
1449                 /* one more inode for the new owner ... */
1450                 qi->lqi_id.qid_uid = attr->la_uid;
1451                 qi->lqi_space      = 1;
1452                 allocated = (attr->la_uid == 0) ? true : false;
1453                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1454                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1455                         rc = 0;
1456                 if (rc)
1457                         RETURN(rc);
1458
1459                 /* and one less inode for the current uid */
1460                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1461                 qi->lqi_space      = -1;
1462                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1463                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1464                         rc = 0;
1465                 if (rc)
1466                         RETURN(rc);
1467
1468                 /* block accounting */
1469                 qi->lqi_is_blk = true;
1470
1471                 /* more blocks for the new owner ... */
1472                 qi->lqi_id.qid_uid = attr->la_uid;
1473                 qi->lqi_space      = bspace;
1474                 allocated = (attr->la_uid == 0) ? true : false;
1475                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1476                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1477                         rc = 0;
1478                 if (rc)
1479                         RETURN(rc);
1480
1481                 /* and finally less blocks for the current owner */
1482                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1483                 qi->lqi_space      = -bspace;
1484                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1485                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1486                         rc = 0;
1487                 if (rc)
1488                         RETURN(rc);
1489         }
1490
1491         if (attr->la_valid & LA_GID &&
1492             attr->la_gid != obj->oo_inode->i_gid) {
1493                 qi->lqi_type = GRPQUOTA;
1494
1495                 /* inode accounting */
1496                 qi->lqi_is_blk = false;
1497
1498                 /* one more inode for the new group owner ... */
1499                 qi->lqi_id.qid_gid = attr->la_gid;
1500                 qi->lqi_space      = 1;
1501                 allocated = (attr->la_gid == 0) ? true : false;
1502                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1503                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1504                         rc = 0;
1505                 if (rc)
1506                         RETURN(rc);
1507
1508                 /* and one less inode for the current gid */
1509                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1510                 qi->lqi_space      = -1;
1511                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1512                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1513                         rc = 0;
1514                 if (rc)
1515                         RETURN(rc);
1516
1517                 /* block accounting */
1518                 qi->lqi_is_blk = true;
1519
1520                 /* more blocks for the new owner ... */
1521                 qi->lqi_id.qid_gid = attr->la_gid;
1522                 qi->lqi_space      = bspace;
1523                 allocated = (attr->la_gid == 0) ? true : false;
1524                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1525                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1526                         rc = 0;
1527                 if (rc)
1528                         RETURN(rc);
1529
1530                 /* and finally less blocks for the current owner */
1531                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1532                 qi->lqi_space      = -bspace;
1533                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1534                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1535                         rc = 0;
1536                 if (rc)
1537                         RETURN(rc);
1538         }
1539
1540         RETURN(rc);
1541 }
1542
1543 static int osd_inode_setattr(const struct lu_env *env,
1544                              struct inode *inode, const struct lu_attr *attr)
1545 {
1546         __u64 bits;
1547
1548         bits = attr->la_valid;
1549
1550         if (bits & LA_ATIME)
1551                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
1552         if (bits & LA_CTIME)
1553                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
1554         if (bits & LA_MTIME)
1555                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
1556         if (bits & LA_SIZE) {
1557                 LDISKFS_I(inode)->i_disksize = attr->la_size;
1558                 i_size_write(inode, attr->la_size);
1559         }
1560
1561 #if 0
1562         /* OSD should not change "i_blocks" which is used by quota.
1563          * "i_blocks" should be changed by ldiskfs only. */
1564         if (bits & LA_BLOCKS)
1565                 inode->i_blocks = attr->la_blocks;
1566 #endif
1567         if (bits & LA_MODE)
1568                 inode->i_mode   = (inode->i_mode & S_IFMT) |
1569                         (attr->la_mode & ~S_IFMT);
1570         if (bits & LA_UID)
1571                 inode->i_uid    = attr->la_uid;
1572         if (bits & LA_GID)
1573                 inode->i_gid    = attr->la_gid;
1574         if (bits & LA_NLINK)
1575                 set_nlink(inode, attr->la_nlink);
1576         if (bits & LA_RDEV)
1577                 inode->i_rdev   = attr->la_rdev;
1578
1579         if (bits & LA_FLAGS) {
1580                 /* always keep S_NOCMTIME */
1581                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
1582                                  S_NOCMTIME;
1583         }
1584         return 0;
1585 }
1586
1587 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
1588 {
1589         if ((attr->la_valid & LA_UID && attr->la_uid != inode->i_uid) ||
1590             (attr->la_valid & LA_GID && attr->la_gid != inode->i_gid)) {
1591                 struct iattr    iattr;
1592                 int             rc;
1593
1594                 iattr.ia_valid = 0;
1595                 if (attr->la_valid & LA_UID)
1596                         iattr.ia_valid |= ATTR_UID;
1597                 if (attr->la_valid & LA_GID)
1598                         iattr.ia_valid |= ATTR_GID;
1599                 iattr.ia_uid = attr->la_uid;
1600                 iattr.ia_gid = attr->la_gid;
1601
1602                 rc = ll_vfs_dq_transfer(inode, &iattr);
1603                 if (rc) {
1604                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
1605                                "enforcement enabled on the ldiskfs filesystem?",
1606                                inode->i_sb->s_id, rc);
1607                         return rc;
1608                 }
1609         }
1610         return 0;
1611 }
1612
1613 static int osd_attr_set(const struct lu_env *env,
1614                         struct dt_object *dt,
1615                         const struct lu_attr *attr,
1616                         struct thandle *handle,
1617                         struct lustre_capa *capa)
1618 {
1619         struct osd_object *obj = osd_dt_obj(dt);
1620         struct inode      *inode;
1621         int rc;
1622
1623         LASSERT(handle != NULL);
1624         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1625         LASSERT(osd_invariant(obj));
1626
1627         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
1628                 return -EACCES;
1629
1630         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
1631
1632         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING)) {
1633                 struct osd_thread_info  *oti  = osd_oti_get(env);
1634                 const struct lu_fid     *fid0 = lu_object_fid(&dt->do_lu);
1635                 struct lu_fid           *fid1 = &oti->oti_fid;
1636                 struct osd_inode_id     *id   = &oti->oti_id;
1637                 struct iam_path_descr   *ipd;
1638                 struct iam_container    *bag;
1639                 struct osd_thandle      *oh;
1640                 int                      rc;
1641
1642                 fid_cpu_to_be(fid1, fid0);
1643                 memset(id, 1, sizeof(*id));
1644                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
1645                                   fid0)->oi_dir.od_container;
1646                 ipd = osd_idx_ipd_get(env, bag);
1647                 if (unlikely(ipd == NULL))
1648                         RETURN(-ENOMEM);
1649
1650                 oh = container_of0(handle, struct osd_thandle, ot_super);
1651                 rc = iam_update(oh->ot_handle, bag, (const struct iam_key *)fid1,
1652                                 (const struct iam_rec *)id, ipd);
1653                 osd_ipd_put(env, bag, ipd);
1654                 return(rc > 0 ? 0 : rc);
1655         }
1656
1657         inode = obj->oo_inode;
1658         ll_vfs_dq_init(inode);
1659
1660         rc = osd_quota_transfer(inode, attr);
1661         if (rc)
1662                 return rc;
1663
1664         spin_lock(&obj->oo_guard);
1665         rc = osd_inode_setattr(env, inode, attr);
1666         spin_unlock(&obj->oo_guard);
1667
1668         if (!rc)
1669                 inode->i_sb->s_op->dirty_inode(inode);
1670         return rc;
1671 }
1672
1673 struct dentry *osd_child_dentry_get(const struct lu_env *env,
1674                                     struct osd_object *obj,
1675                                     const char *name, const int namelen)
1676 {
1677         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
1678 }
1679
1680 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
1681                       cfs_umode_t mode,
1682                       struct dt_allocation_hint *hint,
1683                       struct thandle *th)
1684 {
1685         int result;
1686         struct osd_device  *osd = osd_obj2dev(obj);
1687         struct osd_thandle *oth;
1688         struct dt_object   *parent = NULL;
1689         struct inode       *inode;
1690
1691         LINVRNT(osd_invariant(obj));
1692         LASSERT(obj->oo_inode == NULL);
1693         LASSERT(obj->oo_hl_head == NULL);
1694
1695         if (S_ISDIR(mode) && ldiskfs_pdo) {
1696                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1697                 if (obj->oo_hl_head == NULL)
1698                         return -ENOMEM;
1699         }
1700
1701         oth = container_of(th, struct osd_thandle, ot_super);
1702         LASSERT(oth->ot_handle->h_transaction != NULL);
1703
1704         if (hint && hint->dah_parent)
1705                 parent = hint->dah_parent;
1706
1707         inode = ldiskfs_create_inode(oth->ot_handle,
1708                                      parent ? osd_dt_obj(parent)->oo_inode :
1709                                               osd_sb(osd)->s_root->d_inode,
1710                                      mode);
1711         if (!IS_ERR(inode)) {
1712                 /* Do not update file c/mtime in ldiskfs.
1713                  * NB: don't need any lock because no contention at this
1714                  * early stage */
1715                 inode->i_flags |= S_NOCMTIME;
1716
1717                 /* For new created object, it must be consistent,
1718                  * and it is unnecessary to scrub against it. */
1719                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
1720                 obj->oo_inode = inode;
1721                 result = 0;
1722         } else {
1723                 if (obj->oo_hl_head != NULL) {
1724                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1725                         obj->oo_hl_head = NULL;
1726                 }
1727                 result = PTR_ERR(inode);
1728         }
1729         LINVRNT(osd_invariant(obj));
1730         return result;
1731 }
1732
1733 enum {
1734         OSD_NAME_LEN = 255
1735 };
1736
1737 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
1738                      struct lu_attr *attr,
1739                      struct dt_allocation_hint *hint,
1740                      struct dt_object_format *dof,
1741                      struct thandle *th)
1742 {
1743         int result;
1744         struct osd_thandle *oth;
1745         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX));
1746
1747         LASSERT(S_ISDIR(attr->la_mode));
1748
1749         oth = container_of(th, struct osd_thandle, ot_super);
1750         LASSERT(oth->ot_handle->h_transaction != NULL);
1751         result = osd_mkfile(info, obj, mode, hint, th);
1752
1753         return result;
1754 }
1755
1756 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
1757                         struct lu_attr *attr,
1758                         struct dt_allocation_hint *hint,
1759                         struct dt_object_format *dof,
1760                         struct thandle *th)
1761 {
1762         int result;
1763         struct osd_thandle *oth;
1764         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
1765
1766         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
1767
1768         LASSERT(S_ISREG(attr->la_mode));
1769
1770         oth = container_of(th, struct osd_thandle, ot_super);
1771         LASSERT(oth->ot_handle->h_transaction != NULL);
1772
1773         result = osd_mkfile(info, obj, mode, hint, th);
1774         if (result == 0) {
1775                 LASSERT(obj->oo_inode != NULL);
1776                 if (feat->dif_flags & DT_IND_VARKEY)
1777                         result = iam_lvar_create(obj->oo_inode,
1778                                                  feat->dif_keysize_max,
1779                                                  feat->dif_ptrsize,
1780                                                  feat->dif_recsize_max,
1781                                                  oth->ot_handle);
1782                 else
1783                         result = iam_lfix_create(obj->oo_inode,
1784                                                  feat->dif_keysize_max,
1785                                                  feat->dif_ptrsize,
1786                                                  feat->dif_recsize_max,
1787                                                  oth->ot_handle);
1788
1789         }
1790         return result;
1791 }
1792
1793 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
1794                      struct lu_attr *attr,
1795                      struct dt_allocation_hint *hint,
1796                      struct dt_object_format *dof,
1797                      struct thandle *th)
1798 {
1799         LASSERT(S_ISREG(attr->la_mode));
1800         return osd_mkfile(info, obj, (attr->la_mode &
1801                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
1802 }
1803
1804 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
1805                      struct lu_attr *attr,
1806                      struct dt_allocation_hint *hint,
1807                      struct dt_object_format *dof,
1808                      struct thandle *th)
1809 {
1810         LASSERT(S_ISLNK(attr->la_mode));
1811         return osd_mkfile(info, obj, (attr->la_mode &
1812                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
1813 }
1814
1815 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
1816                      struct lu_attr *attr,
1817                      struct dt_allocation_hint *hint,
1818                      struct dt_object_format *dof,
1819                      struct thandle *th)
1820 {
1821         cfs_umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
1822         int result;
1823
1824         LINVRNT(osd_invariant(obj));
1825         LASSERT(obj->oo_inode == NULL);
1826         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
1827                 S_ISFIFO(mode) || S_ISSOCK(mode));
1828
1829         result = osd_mkfile(info, obj, mode, hint, th);
1830         if (result == 0) {
1831                 LASSERT(obj->oo_inode != NULL);
1832                 /*
1833                  * This inode should be marked dirty for i_rdev.  Currently
1834                  * that is done in the osd_attr_init().
1835                  */
1836                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
1837                                    attr->la_rdev);
1838         }
1839         LINVRNT(osd_invariant(obj));
1840         return result;
1841 }
1842
1843 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
1844                               struct lu_attr *,
1845                               struct dt_allocation_hint *hint,
1846                               struct dt_object_format *dof,
1847                               struct thandle *);
1848
1849 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
1850 {
1851         osd_obj_type_f result;
1852
1853         switch (type) {
1854         case DFT_DIR:
1855                 result = osd_mkdir;
1856                 break;
1857         case DFT_REGULAR:
1858                 result = osd_mkreg;
1859                 break;
1860         case DFT_SYM:
1861                 result = osd_mksym;
1862                 break;
1863         case DFT_NODE:
1864                 result = osd_mknod;
1865                 break;
1866         case DFT_INDEX:
1867                 result = osd_mk_index;
1868                 break;
1869
1870         default:
1871                 LBUG();
1872                 break;
1873         }
1874         return result;
1875 }
1876
1877
1878 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
1879                         struct dt_object *parent, struct dt_object *child,
1880                         cfs_umode_t child_mode)
1881 {
1882         LASSERT(ah);
1883
1884         memset(ah, 0, sizeof(*ah));
1885         ah->dah_parent = parent;
1886         ah->dah_mode = child_mode;
1887 }
1888
1889 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
1890                           struct lu_attr *attr, struct dt_object_format *dof)
1891 {
1892         struct inode   *inode = obj->oo_inode;
1893         __u64           valid = attr->la_valid;
1894         int             result;
1895
1896         attr->la_valid &= ~(LA_TYPE | LA_MODE);
1897
1898         if (dof->dof_type != DFT_NODE)
1899                 attr->la_valid &= ~LA_RDEV;
1900         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
1901                 attr->la_valid &= ~LA_ATIME;
1902         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
1903                 attr->la_valid &= ~LA_CTIME;
1904         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
1905                 attr->la_valid &= ~LA_MTIME;
1906
1907         result = osd_quota_transfer(inode, attr);
1908         if (result)
1909                 return;
1910
1911         if (attr->la_valid != 0) {
1912                 result = osd_inode_setattr(info->oti_env, inode, attr);
1913                 /*
1914                  * The osd_inode_setattr() should always succeed here.  The
1915                  * only error that could be returned is EDQUOT when we are
1916                  * trying to change the UID or GID of the inode. However, this
1917                  * should not happen since quota enforcement is no longer
1918                  * enabled on ldiskfs (lquota takes care of it).
1919                  */
1920                 LASSERTF(result == 0, "%d", result);
1921                 inode->i_sb->s_op->dirty_inode(inode);
1922         }
1923
1924         attr->la_valid = valid;
1925 }
1926
1927 /**
1928  * Helper function for osd_object_create()
1929  *
1930  * \retval 0, on success
1931  */
1932 static int __osd_object_create(struct osd_thread_info *info,
1933                                struct osd_object *obj, struct lu_attr *attr,
1934                                struct dt_allocation_hint *hint,
1935                                struct dt_object_format *dof,
1936                                struct thandle *th)
1937 {
1938         int     result;
1939
1940         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
1941                                                   th);
1942         if (result == 0) {
1943                 osd_attr_init(info, obj, attr, dof);
1944                 osd_object_init0(obj);
1945                 /* bz 24037 */
1946                 if (obj->oo_inode && (obj->oo_inode->i_state & I_NEW))
1947                         unlock_new_inode(obj->oo_inode);
1948         }
1949
1950         return result;
1951 }
1952
1953 /**
1954  * Helper function for osd_object_create()
1955  *
1956  * \retval 0, on success
1957  */
1958 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
1959                            const struct lu_fid *fid, struct thandle *th)
1960 {
1961         struct osd_thread_info *info = osd_oti_get(env);
1962         struct osd_inode_id    *id   = &info->oti_id;
1963         struct osd_device      *osd  = osd_obj2dev(obj);
1964
1965         LASSERT(obj->oo_inode != NULL);
1966
1967         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
1968         return osd_oi_insert(info, osd, fid, id, th);
1969 }
1970
1971 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
1972                    const struct lu_fid *fid, struct lu_seq_range *range)
1973 {
1974         struct seq_server_site  *ss = osd_seq_site(osd);
1975         int                     rc;
1976
1977         if (fid_is_idif(fid)) {
1978                 range->lsr_flags = LU_SEQ_RANGE_OST;
1979                 range->lsr_index = fid_idif_ost_idx(fid);
1980                 return 0;
1981         }
1982
1983         if (!fid_seq_in_fldb(fid_seq(fid))) {
1984                 range->lsr_flags = LU_SEQ_RANGE_MDT;
1985                 if (ss != NULL)
1986                         /* FIXME: If ss is NULL, it suppose not get lsr_index
1987                          * at all */
1988                         range->lsr_index = ss->ss_node_id;
1989                 return 0;
1990         }
1991
1992         LASSERT(ss != NULL);
1993         range->lsr_flags = -1;
1994         rc = fld_server_lookup(env, ss->ss_server_fld, fid_seq(fid), range);
1995         if (rc != 0) {
1996                 CERROR("%s can not find "DFID": rc = %d\n",
1997                        osd_name(osd), PFID(fid), rc);
1998         }
1999         return rc;
2000 }
2001
2002 /*
2003  * Concurrency: no external locking is necessary.
2004  */
2005 static int osd_declare_object_create(const struct lu_env *env,
2006                                      struct dt_object *dt,
2007                                      struct lu_attr *attr,
2008                                      struct dt_allocation_hint *hint,
2009                                      struct dt_object_format *dof,
2010                                      struct thandle *handle)
2011 {
2012         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
2013         struct osd_thandle      *oh;
2014         int                      rc;
2015         ENTRY;
2016
2017         LASSERT(handle != NULL);
2018
2019         oh = container_of0(handle, struct osd_thandle, ot_super);
2020         LASSERT(oh->ot_handle == NULL);
2021
2022         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
2023                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
2024         if (!fid_is_on_ost(osd_oti_get(env), osd_dt_dev(handle->th_dev),
2025                            lu_object_fid(&dt->do_lu)))
2026                 /* Reuse idle OI block may cause additional one OI block
2027                  * to be changed. */
2028                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2029                                 osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
2030
2031         /* If this is directory, then we expect . and .. to be inserted as
2032          * well. The one directory block always needs to be created for the
2033          * directory, so we could use DTO_WRITE_BASE here (GDT, block bitmap,
2034          * block), there is no danger of needing a tree for the first block.
2035          */
2036         if (attr && S_ISDIR(attr->la_mode)) {
2037                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2038                                      osd_dto_credits_noquota[DTO_WRITE_BASE]);
2039                 osd_trans_declare_op(env, oh, OSD_OT_INSERT, 0);
2040         }
2041
2042         if (!attr)
2043                 RETURN(0);
2044
2045         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid, 1, oh,
2046                                    false, false, NULL, false);
2047         if (rc != 0)
2048                 RETURN(rc);
2049
2050         /* It does fld look up inside declare, and the result will be
2051          * added to fld cache, so the following fld lookup inside insert
2052          * does not need send RPC anymore, so avoid send rpc with holding
2053          * transaction */
2054         if (fid_is_norm(lu_object_fid(&dt->do_lu)) &&
2055                 !fid_is_last_id(lu_object_fid(&dt->do_lu)))
2056                 osd_fld_lookup(env, osd_dt_dev(handle->th_dev),
2057                                lu_object_fid(&dt->do_lu), range);
2058
2059
2060         RETURN(rc);
2061 }
2062
2063 static int osd_object_create(const struct lu_env *env, struct dt_object *dt,
2064                              struct lu_attr *attr,
2065                              struct dt_allocation_hint *hint,
2066                              struct dt_object_format *dof,
2067                              struct thandle *th)
2068 {
2069         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2070         struct osd_object      *obj    = osd_dt_obj(dt);
2071         struct osd_thread_info *info   = osd_oti_get(env);
2072         int result;
2073
2074         ENTRY;
2075
2076         LINVRNT(osd_invariant(obj));
2077         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2078         LASSERT(osd_write_locked(env, obj));
2079         LASSERT(th != NULL);
2080
2081         if (unlikely(fid_is_acct(fid)))
2082                 /* Quota files can't be created from the kernel any more,
2083                  * 'tune2fs -O quota' will take care of creating them */
2084                 RETURN(-EPERM);
2085
2086         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2087         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2088
2089         result = __osd_object_create(info, obj, attr, hint, dof, th);
2090         if (result == 0)
2091                 result = __osd_oi_insert(env, obj, fid, th);
2092
2093         LASSERT(ergo(result == 0,
2094                      dt_object_exists(dt) && !dt_object_remote(dt)));
2095
2096         LASSERT(osd_invariant(obj));
2097         RETURN(result);
2098 }
2099
2100 /**
2101  * Called to destroy on-disk representation of the object
2102  *
2103  * Concurrency: must be locked
2104  */
2105 static int osd_declare_object_destroy(const struct lu_env *env,
2106                                       struct dt_object *dt,
2107                                       struct thandle *th)
2108 {
2109         struct osd_object  *obj = osd_dt_obj(dt);
2110         struct inode       *inode = obj->oo_inode;
2111         struct osd_thandle *oh;
2112         int                 rc;
2113         ENTRY;
2114
2115         oh = container_of0(th, struct osd_thandle, ot_super);
2116         LASSERT(oh->ot_handle == NULL);
2117         LASSERT(inode);
2118
2119         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
2120                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
2121         /* Recycle idle OI leaf may cause additional three OI blocks
2122          * to be changed. */
2123         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
2124                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
2125
2126         /* one less inode */
2127         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, -1, oh,
2128                                    false, true, NULL, false);
2129         if (rc)
2130                 RETURN(rc);
2131         /* data to be truncated */
2132         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
2133                                    true, true, NULL, false);
2134         RETURN(rc);
2135 }
2136
2137 static int osd_object_destroy(const struct lu_env *env,
2138                               struct dt_object *dt,
2139                               struct thandle *th)
2140 {
2141         const struct lu_fid    *fid = lu_object_fid(&dt->do_lu);
2142         struct osd_object      *obj = osd_dt_obj(dt);
2143         struct inode           *inode = obj->oo_inode;
2144         struct osd_device      *osd = osd_obj2dev(obj);
2145         struct osd_thandle     *oh;
2146         int                     result;
2147         ENTRY;
2148
2149         oh = container_of0(th, struct osd_thandle, ot_super);
2150         LASSERT(oh->ot_handle);
2151         LASSERT(inode);
2152         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
2153
2154         if (unlikely(fid_is_acct(fid)))
2155                 RETURN(-EPERM);
2156
2157         /* Parallel control for OI scrub. For most of cases, there is no
2158          * lock contention. So it will not affect unlink performance. */
2159         mutex_lock(&inode->i_mutex);
2160         if (S_ISDIR(inode->i_mode)) {
2161                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1);
2162                 /* it will check/delete the agent inode for every dir
2163                  * destory, how to optimize it? unlink performance
2164                  * impaction XXX */
2165                 result = osd_delete_from_agent(env, osd, obj, oh);
2166                 if (result != 0 && result != -ENOENT) {
2167                         CERROR("%s: delete agent inode "DFID": rc = %d\n",
2168                                osd_name(osd), PFID(fid), result);
2169                 }
2170                 spin_lock(&obj->oo_guard);
2171                 clear_nlink(inode);
2172                 spin_unlock(&obj->oo_guard);
2173                 inode->i_sb->s_op->dirty_inode(inode);
2174         }
2175
2176         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
2177
2178         result = osd_oi_delete(osd_oti_get(env), osd, fid, th);
2179         mutex_unlock(&inode->i_mutex);
2180
2181         /* XXX: add to ext3 orphan list */
2182         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
2183
2184         /* not needed in the cache anymore */
2185         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
2186
2187         RETURN(0);
2188 }
2189
2190 static inline int __osd_xattr_set(struct osd_thread_info *info,
2191                                   struct inode *inode, const char *name,
2192                                   const void *buf, int buflen, int fl)
2193 {
2194         struct dentry *dentry = &info->oti_child_dentry;
2195
2196         ll_vfs_dq_init(inode);
2197         dentry->d_inode = inode;
2198         return inode->i_op->setxattr(dentry, name, buf, buflen, fl);
2199 }
2200
2201 /**
2202  * Put the fid into lustre_mdt_attrs, and then place the structure
2203  * inode's ea. This fid should not be altered during the life time
2204  * of the inode.
2205  *
2206  * \retval +ve, on success
2207  * \retval -ve, on error
2208  *
2209  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
2210  */
2211 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
2212                    const struct lu_fid *fid)
2213 {
2214         struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
2215         int                      rc;
2216
2217         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
2218                 return 0;
2219
2220         if (OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF) && fid_is_client_visible(fid))
2221                 return 0;
2222
2223         lustre_lma_init(lma, fid);
2224         lustre_lma_swab(lma);
2225
2226         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma, sizeof(*lma),
2227                              XATTR_CREATE);
2228         /* Someone may created the EA by race. */
2229         if (unlikely(rc == -EEXIST))
2230                 rc = 0;
2231         return rc;
2232 }
2233
2234 /**
2235  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
2236  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
2237  * To have compatilibility with 1.8 ldiskfs driver we need to have
2238  * magic number at start of fid data.
2239  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
2240  * its inmemory API.
2241  */
2242 void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
2243                                   const struct dt_rec *fid)
2244 {
2245         if (!fid_is_client_mdt_visible((const struct lu_fid *)fid)) {
2246                 param->edp_magic = 0;
2247                 return;
2248         }
2249
2250         param->edp_magic = LDISKFS_LUFID_MAGIC;
2251         param->edp_len =  sizeof(struct lu_fid) + 1;
2252         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
2253 }
2254
2255 /**
2256  * Try to read the fid from inode ea into dt_rec.
2257  *
2258  * \param fid object fid.
2259  *
2260  * \retval 0 on success
2261  */
2262 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
2263                           __u32 ino, struct lu_fid *fid,
2264                           struct osd_inode_id *id)
2265 {
2266         struct osd_thread_info *info  = osd_oti_get(env);
2267         struct inode           *inode;
2268         ENTRY;
2269
2270         osd_id_gen(id, ino, OSD_OII_NOGEN);
2271         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
2272         if (IS_ERR(inode))
2273                 RETURN(PTR_ERR(inode));
2274
2275         iput(inode);
2276         RETURN(0);
2277 }
2278
2279 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
2280                                         struct inode *dir,
2281                                         struct inode  *parent_dir,
2282                                         const struct dt_rec *dot_fid,
2283                                         const struct dt_rec *dot_dot_fid,
2284                                         struct osd_thandle *oth)
2285 {
2286         struct ldiskfs_dentry_param *dot_ldp;
2287         struct ldiskfs_dentry_param *dot_dot_ldp;
2288
2289         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
2290         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
2291
2292         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
2293         dot_ldp->edp_magic = 0;
2294         return ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
2295                                         dir, dot_ldp, dot_dot_ldp);
2296 }
2297
2298 /**
2299  * Create an local inode for remote entry
2300  */
2301 static struct inode *osd_create_remote_inode(const struct lu_env *env,
2302                                              struct osd_device *osd,
2303                                              struct osd_object *pobj,
2304                                              const struct lu_fid *fid,
2305                                              struct thandle *th)
2306 {
2307         struct osd_thread_info  *info = osd_oti_get(env);
2308         struct inode            *local;
2309         struct osd_thandle      *oh;
2310         int                     rc;
2311         ENTRY;
2312
2313         LASSERT(th);
2314         oh = container_of(th, struct osd_thandle, ot_super);
2315         LASSERT(oh->ot_handle->h_transaction != NULL);
2316
2317         /* FIXME: Insert index api needs to know the mode of
2318          * the remote object. Just use S_IFDIR for now */
2319         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, S_IFDIR);
2320         if (IS_ERR(local)) {
2321                 CERROR("%s: create local error %d\n", osd_name(osd),
2322                        (int)PTR_ERR(local));
2323                 RETURN(local);
2324         }
2325
2326         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
2327                 (const struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
2328                 (const struct dt_rec *)fid, oh);
2329         if (rc != 0) {
2330                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
2331                         osd_name(osd), PFID(fid), rc);
2332                 RETURN(ERR_PTR(rc));
2333         }
2334
2335         RETURN(local);
2336 }
2337
2338 /**
2339  * Delete local inode for remote entry
2340  */
2341 static int osd_delete_remote_inode(const struct lu_env *env,
2342                                    struct osd_device *osd,
2343                                    const struct lu_fid *fid,
2344                                     __u32 ino, struct osd_thandle *oh)
2345 {
2346         struct osd_thread_info  *oti = osd_oti_get(env);
2347         struct osd_inode_id     *id = &oti->oti_id;
2348         struct inode            *inode;
2349         ENTRY;
2350
2351         id->oii_ino = le32_to_cpu(ino);
2352         id->oii_gen = OSD_OII_NOGEN;
2353         inode = osd_iget(oti, osd, id);
2354         if (IS_ERR(inode)) {
2355                 CERROR("%s: iget error "DFID" id %u:%u\n", osd_name(osd),
2356                        PFID(fid), id->oii_ino, id->oii_gen);
2357                 RETURN(PTR_ERR(inode));
2358         }
2359
2360         clear_nlink(inode);
2361         mark_inode_dirty(inode);
2362         CDEBUG(D_INODE, "%s: delete remote inode "DFID" %lu\n",
2363                 osd_name(osd), PFID(fid), inode->i_ino);
2364         iput(inode);
2365         RETURN(0);
2366 }
2367
2368 /**
2369  * OSD layer object create function for interoperability mode (b11826).
2370  * This is mostly similar to osd_object_create(). Only difference being, fid is
2371  * inserted into inode ea here.
2372  *
2373  * \retval   0, on success
2374  * \retval -ve, on error
2375  */
2376 static int osd_object_ea_create(const struct lu_env *env, struct dt_object *dt,
2377                                 struct lu_attr *attr,
2378                                 struct dt_allocation_hint *hint,
2379                                 struct dt_object_format *dof,
2380                                 struct thandle *th)
2381 {
2382         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2383         struct osd_object      *obj    = osd_dt_obj(dt);
2384         struct osd_thread_info *info   = osd_oti_get(env);
2385         int                     result;
2386
2387         ENTRY;
2388
2389         LASSERT(osd_invariant(obj));
2390         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2391         LASSERT(osd_write_locked(env, obj));
2392         LASSERT(th != NULL);
2393
2394         if (unlikely(fid_is_acct(fid)))
2395                 /* Quota files can't be created from the kernel any more,
2396                  * 'tune2fs -O quota' will take care of creating them */
2397                 RETURN(-EPERM);
2398
2399         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2400         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2401
2402         result = __osd_object_create(info, obj, attr, hint, dof, th);
2403         if ((result == 0) &&
2404             (fid_is_last_id(fid) ||
2405              !fid_is_on_ost(info, osd_dt_dev(th->th_dev), fid)))
2406                 result = osd_ea_fid_set(info, obj->oo_inode, fid);
2407
2408         if (result == 0)
2409                 result = __osd_oi_insert(env, obj, fid, th);
2410
2411         LASSERT(ergo(result == 0,
2412                      dt_object_exists(dt) && !dt_object_remote(dt)));
2413         LINVRNT(osd_invariant(obj));
2414         RETURN(result);
2415 }
2416
2417 static int osd_declare_object_ref_add(const struct lu_env *env,
2418                                       struct dt_object *dt,
2419                                       struct thandle *handle)
2420 {
2421         struct osd_thandle       *oh;
2422
2423         /* it's possible that object doesn't exist yet */
2424         LASSERT(handle != NULL);
2425
2426         oh = container_of0(handle, struct osd_thandle, ot_super);
2427         LASSERT(oh->ot_handle == NULL);
2428
2429         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
2430                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2431
2432         return 0;
2433 }
2434
2435 /*
2436  * Concurrency: @dt is write locked.
2437  */
2438 static int osd_object_ref_add(const struct lu_env *env,
2439                               struct dt_object *dt, struct thandle *th)
2440 {
2441         struct osd_object *obj = osd_dt_obj(dt);
2442         struct inode      *inode = obj->oo_inode;
2443
2444         LINVRNT(osd_invariant(obj));
2445         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2446         LASSERT(osd_write_locked(env, obj));
2447         LASSERT(th != NULL);
2448
2449         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
2450
2451         /*
2452          * DIR_NLINK feature is set for compatibility reasons if:
2453          * 1) nlinks > LDISKFS_LINK_MAX, or
2454          * 2) nlinks == 2, since this indicates i_nlink was previously 1.
2455          *
2456          * It is easier to always set this flag (rather than check and set),
2457          * since it has less overhead, and the superblock will be dirtied
2458          * at some point. Both e2fsprogs and any Lustre-supported ldiskfs
2459          * do not actually care whether this flag is set or not.
2460          */
2461         spin_lock(&obj->oo_guard);
2462         /* inc_nlink from 0 may cause WARN_ON */
2463         if(inode->i_nlink == 0)
2464                 set_nlink(inode, 1);
2465         else
2466                 inc_nlink(inode);
2467         if (S_ISDIR(inode->i_mode) && inode->i_nlink > 1) {
2468                 if (inode->i_nlink >= LDISKFS_LINK_MAX ||
2469                     inode->i_nlink == 2)
2470                         set_nlink(inode, 1);
2471         }
2472         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
2473         spin_unlock(&obj->oo_guard);
2474         inode->i_sb->s_op->dirty_inode(inode);
2475         LINVRNT(osd_invariant(obj));
2476
2477         return 0;
2478 }
2479
2480 static int osd_declare_object_ref_del(const struct lu_env *env,
2481                                       struct dt_object *dt,
2482                                       struct thandle *handle)
2483 {
2484         struct osd_thandle *oh;
2485
2486         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2487         LASSERT(handle != NULL);
2488
2489         oh = container_of0(handle, struct osd_thandle, ot_super);
2490         LASSERT(oh->ot_handle == NULL);
2491
2492         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
2493                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2494
2495         return 0;
2496 }
2497
2498 /*
2499  * Concurrency: @dt is write locked.
2500  */
2501 static int osd_object_ref_del(const struct lu_env *env, struct dt_object *dt,
2502                               struct thandle *th)
2503 {
2504         struct osd_object *obj = osd_dt_obj(dt);
2505         struct inode      *inode = obj->oo_inode;
2506
2507         LINVRNT(osd_invariant(obj));
2508         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2509         LASSERT(osd_write_locked(env, obj));
2510         LASSERT(th != NULL);
2511
2512         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
2513
2514         spin_lock(&obj->oo_guard);
2515         LASSERT(inode->i_nlink > 0);
2516         drop_nlink(inode);
2517         /* If this is/was a many-subdir directory (nlink > LDISKFS_LINK_MAX)
2518          * then the nlink count is 1. Don't let it be set to 0 or the directory
2519          * inode will be deleted incorrectly. */
2520         if (S_ISDIR(inode->i_mode) && inode->i_nlink == 0)
2521                 set_nlink(inode, 1);
2522         spin_unlock(&obj->oo_guard);
2523         inode->i_sb->s_op->dirty_inode(inode);
2524         LINVRNT(osd_invariant(obj));
2525
2526         return 0;
2527 }
2528
2529 /*
2530  * Get the 64-bit version for an inode.
2531  */
2532 static int osd_object_version_get(const struct lu_env *env,
2533                                   struct dt_object *dt, dt_obj_version_t *ver)
2534 {
2535         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2536
2537         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
2538                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2539         *ver = LDISKFS_I(inode)->i_fs_version;
2540         return 0;
2541 }
2542
2543 /*
2544  * Concurrency: @dt is read locked.
2545  */
2546 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
2547                          struct lu_buf *buf, const char *name,
2548                          struct lustre_capa *capa)
2549 {
2550         struct osd_object      *obj    = osd_dt_obj(dt);
2551         struct inode           *inode  = obj->oo_inode;
2552         struct osd_thread_info *info   = osd_oti_get(env);
2553         struct dentry          *dentry = &info->oti_obj_dentry;
2554
2555         /* version get is not real XATTR but uses xattr API */
2556         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2557                 /* for version we are just using xattr API but change inode
2558                  * field instead */
2559                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2560                 osd_object_version_get(env, dt, buf->lb_buf);
2561                 return sizeof(dt_obj_version_t);
2562         }
2563
2564         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2565         LASSERT(inode->i_op != NULL && inode->i_op->getxattr != NULL);
2566
2567         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2568                 return -EACCES;
2569
2570         return __osd_xattr_get(inode, dentry, name, buf->lb_buf, buf->lb_len);
2571 }
2572
2573
2574 static int osd_declare_xattr_set(const struct lu_env *env,
2575                                  struct dt_object *dt,
2576                                  const struct lu_buf *buf, const char *name,
2577                                  int fl, struct thandle *handle)
2578 {
2579         struct osd_thandle *oh;
2580
2581         LASSERT(handle != NULL);
2582
2583         oh = container_of0(handle, struct osd_thandle, ot_super);
2584         LASSERT(oh->ot_handle == NULL);
2585
2586         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2587                              strcmp(name, XATTR_NAME_VERSION) == 0 ?
2588                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] :
2589                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2590
2591         return 0;
2592 }
2593
2594 /*
2595  * Set the 64-bit version for object
2596  */
2597 static void osd_object_version_set(const struct lu_env *env,
2598                                    struct dt_object *dt,
2599                                    dt_obj_version_t *new_version)
2600 {
2601         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2602
2603         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
2604                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2605
2606         LDISKFS_I(inode)->i_fs_version = *new_version;
2607         /** Version is set after all inode operations are finished,
2608          *  so we should mark it dirty here */
2609         inode->i_sb->s_op->dirty_inode(inode);
2610 }
2611
2612 /*
2613  * Concurrency: @dt is write locked.
2614  */
2615 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
2616                          const struct lu_buf *buf, const char *name, int fl,
2617                          struct thandle *handle, struct lustre_capa *capa)
2618 {
2619         struct osd_object      *obj      = osd_dt_obj(dt);
2620         struct inode           *inode    = obj->oo_inode;
2621         struct osd_thread_info *info     = osd_oti_get(env);
2622         int                     fs_flags = 0;
2623
2624         LASSERT(handle != NULL);
2625
2626         /* version set is not real XATTR */
2627         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2628                 /* for version we are just using xattr API but change inode
2629                  * field instead */
2630                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2631                 osd_object_version_set(env, dt, buf->lb_buf);
2632                 return sizeof(dt_obj_version_t);
2633         }
2634
2635         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2636                 return -EACCES;
2637
2638         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2639         if (fl & LU_XATTR_REPLACE)
2640                 fs_flags |= XATTR_REPLACE;
2641
2642         if (fl & LU_XATTR_CREATE)
2643                 fs_flags |= XATTR_CREATE;
2644
2645         return __osd_xattr_set(info, inode, name, buf->lb_buf, buf->lb_len,
2646                                fs_flags);
2647 }
2648
2649 /*
2650  * Concurrency: @dt is read locked.
2651  */
2652 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
2653                           struct lu_buf *buf, struct lustre_capa *capa)
2654 {
2655         struct osd_object      *obj    = osd_dt_obj(dt);
2656         struct inode           *inode  = obj->oo_inode;
2657         struct osd_thread_info *info   = osd_oti_get(env);
2658         struct dentry          *dentry = &info->oti_obj_dentry;
2659
2660         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2661         LASSERT(inode->i_op != NULL && inode->i_op->listxattr != NULL);
2662         LASSERT(osd_read_locked(env, obj) || osd_write_locked(env, obj));
2663
2664         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2665                 return -EACCES;
2666
2667         dentry->d_inode = inode;
2668         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
2669 }
2670
2671 static int osd_declare_xattr_del(const struct lu_env *env,
2672                                  struct dt_object *dt, const char *name,
2673                                  struct thandle *handle)
2674 {
2675         struct osd_thandle *oh;
2676
2677         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2678         LASSERT(handle != NULL);
2679
2680         oh = container_of0(handle, struct osd_thandle, ot_super);
2681         LASSERT(oh->ot_handle == NULL);
2682
2683         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2684                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2685
2686         return 0;
2687 }
2688
2689 /*
2690  * Concurrency: @dt is write locked.
2691  */
2692 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
2693                          const char *name, struct thandle *handle,
2694                          struct lustre_capa *capa)
2695 {
2696         struct osd_object      *obj    = osd_dt_obj(dt);
2697         struct inode           *inode  = obj->oo_inode;
2698         struct osd_thread_info *info   = osd_oti_get(env);
2699         struct dentry          *dentry = &info->oti_obj_dentry;
2700         int                     rc;
2701
2702         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2703         LASSERT(inode->i_op != NULL && inode->i_op->removexattr != NULL);
2704         LASSERT(handle != NULL);
2705
2706         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2707                 return -EACCES;
2708
2709         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2710
2711         ll_vfs_dq_init(inode);
2712         dentry->d_inode = inode;
2713         rc = inode->i_op->removexattr(dentry, name);
2714         return rc;
2715 }
2716
2717 static struct obd_capa *osd_capa_get(const struct lu_env *env,
2718                                      struct dt_object *dt,
2719                                      struct lustre_capa *old,
2720                                      __u64 opc)
2721 {
2722         struct osd_thread_info *info = osd_oti_get(env);
2723         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
2724         struct osd_object *obj = osd_dt_obj(dt);
2725         struct osd_device *dev = osd_obj2dev(obj);
2726         struct lustre_capa_key *key = &info->oti_capa_key;
2727         struct lustre_capa *capa = &info->oti_capa;
2728         struct obd_capa *oc;
2729         struct md_capainfo *ci;
2730         int rc;
2731         ENTRY;
2732
2733         if (!dev->od_fl_capa)
2734                 RETURN(ERR_PTR(-ENOENT));
2735
2736         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2737         LINVRNT(osd_invariant(obj));
2738
2739         /* renewal sanity check */
2740         if (old && osd_object_auth(env, dt, old, opc))
2741                 RETURN(ERR_PTR(-EACCES));
2742
2743         ci = md_capainfo(env);
2744         if (unlikely(!ci))
2745                 RETURN(ERR_PTR(-ENOENT));
2746
2747         switch (ci->mc_auth) {
2748         case LC_ID_NONE:
2749                 RETURN(NULL);
2750         case LC_ID_PLAIN:
2751                 capa->lc_uid = obj->oo_inode->i_uid;
2752                 capa->lc_gid = obj->oo_inode->i_gid;
2753                 capa->lc_flags = LC_ID_PLAIN;
2754                 break;
2755         case LC_ID_CONVERT: {
2756                 __u32 d[4], s[4];
2757
2758                 s[0] = obj->oo_inode->i_uid;
2759                 cfs_get_random_bytes(&(s[1]), sizeof(__u32));
2760                 s[2] = obj->oo_inode->i_gid;
2761                 cfs_get_random_bytes(&(s[3]), sizeof(__u32));
2762                 rc = capa_encrypt_id(d, s, key->lk_key, CAPA_HMAC_KEY_MAX_LEN);
2763                 if (unlikely(rc))
2764                         RETURN(ERR_PTR(rc));
2765
2766                 capa->lc_uid   = ((__u64)d[1] << 32) | d[0];
2767                 capa->lc_gid   = ((__u64)d[3] << 32) | d[2];
2768                 capa->lc_flags = LC_ID_CONVERT;
2769                 break;
2770         }
2771         default:
2772                 RETURN(ERR_PTR(-EINVAL));
2773         }
2774
2775         capa->lc_fid = *fid;
2776         capa->lc_opc = opc;
2777         capa->lc_flags |= dev->od_capa_alg << 24;
2778         capa->lc_timeout = dev->od_capa_timeout;
2779         capa->lc_expiry = 0;
2780
2781         oc = capa_lookup(dev->od_capa_hash, capa, 1);
2782         if (oc) {
2783                 LASSERT(!capa_is_expired(oc));
2784                 RETURN(oc);
2785         }
2786
2787         spin_lock(&capa_lock);
2788         *key = dev->od_capa_keys[1];
2789         spin_unlock(&capa_lock);
2790
2791         capa->lc_keyid = key->lk_keyid;
2792         capa->lc_expiry = cfs_time_current_sec() + dev->od_capa_timeout;
2793
2794         rc = capa_hmac(capa->lc_hmac, capa, key->lk_key);
2795         if (rc) {
2796                 DEBUG_CAPA(D_ERROR, capa, "HMAC failed: %d for", rc);
2797                 RETURN(ERR_PTR(rc));
2798         }
2799
2800         oc = capa_add(dev->od_capa_hash, capa);
2801         RETURN(oc);
2802 }
2803
2804 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt)
2805 {
2806         struct osd_object       *obj    = osd_dt_obj(dt);
2807         struct inode            *inode  = obj->oo_inode;
2808         struct osd_thread_info  *info   = osd_oti_get(env);
2809         struct dentry           *dentry = &info->oti_obj_dentry;
2810         struct file             *file   = &info->oti_file;
2811         int                     rc;
2812
2813         ENTRY;
2814
2815         dentry->d_inode = inode;
2816         file->f_dentry = dentry;
2817         file->f_mapping = inode->i_mapping;
2818         file->f_op = inode->i_fop;
2819         mutex_lock(&inode->i_mutex);
2820         rc = file->f_op->fsync(file, dentry, 0);
2821         mutex_unlock(&inode->i_mutex);
2822         RETURN(rc);
2823 }
2824
2825 static int osd_data_get(const struct lu_env *env, struct dt_object *dt,
2826                         void **data)
2827 {
2828         struct osd_object *obj = osd_dt_obj(dt);
2829         ENTRY;
2830
2831         *data = (void *)obj->oo_inode;
2832         RETURN(0);
2833 }
2834
2835 /*
2836  * Index operations.
2837  */
2838
2839 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
2840                            const struct dt_index_features *feat)
2841 {
2842         struct iam_descr *descr;
2843
2844         if (osd_object_is_root(o))
2845                 return feat == &dt_directory_features;
2846
2847         LASSERT(o->oo_dir != NULL);
2848
2849         descr = o->oo_dir->od_container.ic_descr;
2850         if (feat == &dt_directory_features) {
2851                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
2852                         return 1;
2853                 else
2854                         return 0;
2855         } else {
2856                 return
2857                         feat->dif_keysize_min <= descr->id_key_size &&
2858                         descr->id_key_size <= feat->dif_keysize_max &&
2859                         feat->dif_recsize_min <= descr->id_rec_size &&
2860                         descr->id_rec_size <= feat->dif_recsize_max &&
2861                         !(feat->dif_flags & (DT_IND_VARKEY |
2862                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
2863                         ergo(feat->dif_flags & DT_IND_UPDATE,
2864                              1 /* XXX check that object (and file system) is
2865                                 * writable */);
2866         }
2867 }
2868
2869 static int osd_iam_container_init(const struct lu_env *env,
2870                                   struct osd_object *obj,
2871                                   struct osd_directory *dir)
2872 {
2873         struct iam_container *bag = &dir->od_container;
2874         int result;
2875
2876         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
2877         if (result != 0)
2878                 return result;
2879
2880         result = iam_container_setup(bag);
2881         if (result == 0)
2882                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
2883         else
2884                 iam_container_fini(bag);
2885
2886         return result;
2887 }
2888
2889
2890 /*
2891  * Concurrency: no external locking is necessary.
2892  */
2893 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
2894                          const struct dt_index_features *feat)
2895 {
2896         int                      result;
2897         int                      skip_iam = 0;
2898         struct osd_object       *obj = osd_dt_obj(dt);
2899
2900         LINVRNT(osd_invariant(obj));
2901
2902         if (osd_object_is_root(obj)) {
2903                 dt->do_index_ops = &osd_index_ea_ops;
2904                 result = 0;
2905         } else if (feat == &dt_directory_features) {
2906                 dt->do_index_ops = &osd_index_ea_ops;
2907                 if (obj->oo_inode != NULL && S_ISDIR(obj->oo_inode->i_mode))
2908                         result = 0;
2909                 else
2910                         result = -ENOTDIR;
2911                 skip_iam = 1;
2912         } else if (unlikely(feat == &dt_otable_features)) {
2913                 dt->do_index_ops = &osd_otable_ops;
2914                 return 0;
2915         } else if (unlikely(feat == &dt_acct_features)) {
2916                 dt->do_index_ops = &osd_acct_index_ops;
2917                 result = 0;
2918                 skip_iam = 1;
2919         } else if (!osd_has_index(obj)) {
2920                 struct osd_directory *dir;
2921
2922                 OBD_ALLOC_PTR(dir);
2923                 if (dir != NULL) {
2924
2925                         spin_lock(&obj->oo_guard);
2926                         if (obj->oo_dir == NULL)
2927                                 obj->oo_dir = dir;
2928                         else
2929                                 /*
2930                                  * Concurrent thread allocated container data.
2931                                  */
2932                                 OBD_FREE_PTR(dir);
2933                         spin_unlock(&obj->oo_guard);
2934                         /*
2935                          * Now, that we have container data, serialize its
2936                          * initialization.
2937                          */
2938                         down_write(&obj->oo_ext_idx_sem);
2939                         /*
2940                          * recheck under lock.
2941                          */
2942                         if (!osd_has_index(obj))
2943                                 result = osd_iam_container_init(env, obj, dir);
2944                         else
2945                                 result = 0;
2946                         up_write(&obj->oo_ext_idx_sem);
2947                 } else {
2948                         result = -ENOMEM;
2949                 }
2950         } else {
2951                 result = 0;
2952         }
2953
2954         if (result == 0 && skip_iam == 0) {
2955                 if (!osd_iam_index_probe(env, obj, feat))
2956                         result = -ENOTDIR;
2957         }
2958         LINVRNT(osd_invariant(obj));
2959
2960         if (is_quota_glb_feat(feat))
2961                 result = osd_quota_migration(env, dt, feat);
2962
2963         return result;
2964 }
2965
2966 static int osd_otable_it_attr_get(const struct lu_env *env,
2967                                  struct dt_object *dt,
2968                                  struct lu_attr *attr,
2969                                  struct lustre_capa *capa)
2970 {
2971         attr->la_valid = 0;
2972         return 0;
2973 }
2974
2975 static const struct dt_object_operations osd_obj_ops = {
2976         .do_read_lock         = osd_object_read_lock,
2977         .do_write_lock        = osd_object_write_lock,
2978         .do_read_unlock       = osd_object_read_unlock,
2979         .do_write_unlock      = osd_object_write_unlock,
2980         .do_write_locked      = osd_object_write_locked,
2981         .do_attr_get          = osd_attr_get,
2982         .do_declare_attr_set  = osd_declare_attr_set,
2983         .do_attr_set          = osd_attr_set,
2984         .do_ah_init           = osd_ah_init,
2985         .do_declare_create    = osd_declare_object_create,
2986         .do_create            = osd_object_create,
2987         .do_declare_destroy   = osd_declare_object_destroy,
2988         .do_destroy           = osd_object_destroy,
2989         .do_index_try         = osd_index_try,
2990         .do_declare_ref_add   = osd_declare_object_ref_add,
2991         .do_ref_add           = osd_object_ref_add,
2992         .do_declare_ref_del   = osd_declare_object_ref_del,
2993         .do_ref_del           = osd_object_ref_del,
2994         .do_xattr_get         = osd_xattr_get,
2995         .do_declare_xattr_set = osd_declare_xattr_set,
2996         .do_xattr_set         = osd_xattr_set,
2997         .do_declare_xattr_del = osd_declare_xattr_del,
2998         .do_xattr_del         = osd_xattr_del,
2999         .do_xattr_list        = osd_xattr_list,
3000         .do_capa_get          = osd_capa_get,
3001         .do_object_sync       = osd_object_sync,
3002         .do_data_get          = osd_data_get,
3003 };
3004
3005 /**
3006  * dt_object_operations for interoperability mode
3007  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
3008  */
3009 static const struct dt_object_operations osd_obj_ea_ops = {
3010         .do_read_lock         = osd_object_read_lock,
3011         .do_write_lock        = osd_object_write_lock,
3012         .do_read_unlock       = osd_object_read_unlock,
3013         .do_write_unlock      = osd_object_write_unlock,
3014         .do_write_locked      = osd_object_write_locked,
3015         .do_attr_get          = osd_attr_get,
3016         .do_declare_attr_set  = osd_declare_attr_set,
3017         .do_attr_set          = osd_attr_set,
3018         .do_ah_init           = osd_ah_init,
3019         .do_declare_create    = osd_declare_object_create,
3020         .do_create            = osd_object_ea_create,
3021         .do_declare_destroy   = osd_declare_object_destroy,
3022         .do_destroy           = osd_object_destroy,
3023         .do_index_try         = osd_index_try,
3024         .do_declare_ref_add   = osd_declare_object_ref_add,
3025         .do_ref_add           = osd_object_ref_add,
3026         .do_declare_ref_del   = osd_declare_object_ref_del,
3027         .do_ref_del           = osd_object_ref_del,
3028         .do_xattr_get         = osd_xattr_get,
3029         .do_declare_xattr_set = osd_declare_xattr_set,
3030         .do_xattr_set         = osd_xattr_set,
3031         .do_declare_xattr_del = osd_declare_xattr_del,
3032         .do_xattr_del         = osd_xattr_del,
3033         .do_xattr_list        = osd_xattr_list,
3034         .do_capa_get          = osd_capa_get,
3035         .do_object_sync       = osd_object_sync,
3036         .do_data_get          = osd_data_get,
3037 };
3038
3039 static const struct dt_object_operations osd_obj_otable_it_ops = {
3040         .do_attr_get    = osd_otable_it_attr_get,
3041         .do_index_try   = osd_index_try,
3042 };
3043
3044 static int osd_index_declare_iam_delete(const struct lu_env *env,
3045                                         struct dt_object *dt,
3046                                         const struct dt_key *key,
3047                                         struct thandle *handle)
3048 {
3049         struct osd_thandle    *oh;
3050
3051         oh = container_of0(handle, struct osd_thandle, ot_super);
3052         LASSERT(oh->ot_handle == NULL);
3053
3054         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3055                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3056
3057         return 0;
3058 }
3059
3060 /**
3061  *      delete a (key, value) pair from index \a dt specified by \a key
3062  *
3063  *      \param  dt      osd index object
3064  *      \param  key     key for index
3065  *      \param  rec     record reference
3066  *      \param  handle  transaction handler
3067  *
3068  *      \retval  0  success
3069  *      \retval -ve   failure
3070  */
3071
3072 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
3073                                 const struct dt_key *key,
3074                                 struct thandle *handle,
3075                                 struct lustre_capa *capa)
3076 {
3077         struct osd_thread_info *oti = osd_oti_get(env);
3078         struct osd_object      *obj = osd_dt_obj(dt);
3079         struct osd_thandle     *oh;
3080         struct iam_path_descr  *ipd;
3081         struct iam_container   *bag = &obj->oo_dir->od_container;
3082         int                     rc;
3083
3084         ENTRY;
3085
3086         LINVRNT(osd_invariant(obj));
3087         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3088         LASSERT(bag->ic_object == obj->oo_inode);
3089         LASSERT(handle != NULL);
3090
3091         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3092                 RETURN(-EACCES);
3093
3094         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3095
3096         ipd = osd_idx_ipd_get(env, bag);
3097         if (unlikely(ipd == NULL))
3098                 RETURN(-ENOMEM);
3099
3100         oh = container_of0(handle, struct osd_thandle, ot_super);
3101         LASSERT(oh->ot_handle != NULL);
3102         LASSERT(oh->ot_handle->h_transaction != NULL);
3103
3104         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3105                 /* swab quota uid/gid provided by caller */
3106                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3107                 key = (const struct dt_key *)&oti->oti_quota_id;
3108         }
3109
3110         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
3111         osd_ipd_put(env, bag, ipd);
3112         LINVRNT(osd_invariant(obj));
3113         RETURN(rc);
3114 }
3115
3116 static int osd_index_declare_ea_delete(const struct lu_env *env,
3117                                        struct dt_object *dt,
3118                                        const struct dt_key *key,
3119                                        struct thandle *handle)
3120 {
3121         struct osd_thandle *oh;
3122         struct inode       *inode;
3123         int                 rc;
3124         ENTRY;
3125
3126         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3127         LASSERT(handle != NULL);
3128
3129         oh = container_of0(handle, struct osd_thandle, ot_super);
3130         LASSERT(oh->ot_handle == NULL);
3131
3132         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3133                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3134
3135         inode = osd_dt_obj(dt)->oo_inode;
3136         LASSERT(inode);
3137
3138         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
3139                                    true, true, NULL, false);
3140         RETURN(rc);
3141 }
3142
3143 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3144                                           struct dt_rec *fid)
3145 {
3146         struct osd_fid_pack *rec;
3147         int                  rc = -ENODATA;
3148
3149         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3150                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3151                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3152         }
3153         return rc;
3154 }
3155
3156 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
3157                           struct lu_fid *fid)
3158 {
3159         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
3160         struct seq_server_site  *ss = osd_seq_site(osd);
3161         int                     rc;
3162         ENTRY;
3163
3164         /* Those FID seqs, which are not in FLDB, must be local seq */
3165         if (unlikely(!fid_seq_in_fldb(fid_seq(fid)) || ss == NULL))
3166                 RETURN(0);
3167
3168         rc = osd_fld_lookup(env, osd, fid, range);
3169         if (rc != 0) {
3170                 CERROR("%s: Can not lookup fld for "DFID"\n",
3171                        osd_name(osd), PFID(fid));
3172                 RETURN(rc);
3173         }
3174
3175         RETURN(ss->ss_node_id != range->lsr_index);
3176 }
3177
3178 /**
3179  * Index delete function for interoperability mode (b11826).
3180  * It will remove the directory entry added by osd_index_ea_insert().
3181  * This entry is needed to maintain name->fid mapping.
3182  *
3183  * \param key,  key i.e. file entry to be deleted
3184  *
3185  * \retval   0, on success
3186  * \retval -ve, on error
3187  */
3188 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3189                                const struct dt_key *key,
3190                                struct thandle *handle,
3191                                struct lustre_capa *capa)
3192 {
3193         struct osd_object          *obj    = osd_dt_obj(dt);
3194         struct inode               *dir    = obj->oo_inode;
3195         struct dentry              *dentry;
3196         struct osd_thandle         *oh;
3197         struct ldiskfs_dir_entry_2 *de = NULL;
3198         struct buffer_head         *bh;
3199         struct htree_lock          *hlock = NULL;
3200         struct lu_fid              *fid = &osd_oti_get(env)->oti_fid;
3201         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
3202         int                        rc;
3203         ENTRY;
3204
3205         LINVRNT(osd_invariant(obj));
3206         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3207         LASSERT(handle != NULL);
3208
3209         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3210
3211         oh = container_of(handle, struct osd_thandle, ot_super);
3212         LASSERT(oh->ot_handle != NULL);
3213         LASSERT(oh->ot_handle->h_transaction != NULL);
3214
3215         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3216                 RETURN(-EACCES);
3217
3218         ll_vfs_dq_init(dir);
3219         dentry = osd_child_dentry_get(env, obj,
3220                                       (char *)key, strlen((char *)key));
3221
3222         if (obj->oo_hl_head != NULL) {
3223                 hlock = osd_oti_get(env)->oti_hlock;
3224                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3225                                    dir, LDISKFS_HLOCK_DEL);
3226         } else {
3227                 down_write(&obj->oo_ext_idx_sem);
3228         }
3229
3230         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
3231         if (bh) {
3232                 rc = ldiskfs_delete_entry(oh->ot_handle,
3233                                           dir, de, bh);
3234                 brelse(bh);
3235         } else {
3236                 rc = -ENOENT;
3237         }
3238         if (hlock != NULL)
3239                 ldiskfs_htree_unlock(hlock);
3240         else
3241                 up_write(&obj->oo_ext_idx_sem);
3242
3243         if (rc != 0)
3244                 GOTO(out, rc);
3245
3246         /* For inode on the remote MDT, .. will point to
3247          * /Agent directory. So do not try to lookup/delete
3248          * remote inode for .. */
3249         if (strcmp((char *)key, dotdot) == 0)
3250                 GOTO(out, rc = 0);
3251
3252         LASSERT(de != NULL);
3253         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
3254         if (rc == 0 && osd_remote_fid(env, osd, fid)) {
3255                 __u32 ino = le32_to_cpu(de->inode);
3256
3257                 rc = osd_delete_remote_inode(env, osd, fid, ino, oh);
3258                 if (rc != 0)
3259                         CERROR("%s: del local inode "DFID": rc = %d\n",
3260                                 osd_name(osd), PFID(fid), rc);
3261         } else {
3262                 if (rc == -ENODATA)
3263                         rc = 0;
3264         }
3265 out:
3266
3267         LASSERT(osd_invariant(obj));
3268         RETURN(rc);
3269 }
3270
3271 /**
3272  *      Lookup index for \a key and copy record to \a rec.
3273  *
3274  *      \param  dt      osd index object
3275  *      \param  key     key for index
3276  *      \param  rec     record reference
3277  *
3278  *      \retval  +ve  success : exact mach
3279  *      \retval  0    return record with key not greater than \a key
3280  *      \retval -ve   failure
3281  */
3282 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
3283                                 struct dt_rec *rec, const struct dt_key *key,
3284                                 struct lustre_capa *capa)
3285 {
3286         struct osd_object      *obj = osd_dt_obj(dt);
3287         struct iam_path_descr  *ipd;
3288         struct iam_container   *bag = &obj->oo_dir->od_container;
3289         struct osd_thread_info *oti = osd_oti_get(env);
3290         struct iam_iterator    *it = &oti->oti_idx_it;
3291         struct iam_rec         *iam_rec;
3292         int                     rc;
3293
3294         ENTRY;
3295
3296         LASSERT(osd_invariant(obj));
3297         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3298         LASSERT(bag->ic_object == obj->oo_inode);
3299
3300         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
3301                 RETURN(-EACCES);
3302
3303         ipd = osd_idx_ipd_get(env, bag);
3304         if (IS_ERR(ipd))
3305                 RETURN(-ENOMEM);
3306
3307         /* got ipd now we can start iterator. */
3308         iam_it_init(it, bag, 0, ipd);
3309
3310         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3311                 /* swab quota uid/gid provided by caller */
3312                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3313                 key = (const struct dt_key *)&oti->oti_quota_id;
3314         }
3315
3316         rc = iam_it_get(it, (struct iam_key *)key);
3317         if (rc >= 0) {
3318                 if (S_ISDIR(obj->oo_inode->i_mode))
3319                         iam_rec = (struct iam_rec *)oti->oti_ldp;
3320                 else
3321                         iam_rec = (struct iam_rec *) rec;
3322
3323                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
3324
3325                 if (S_ISDIR(obj->oo_inode->i_mode))
3326                         osd_fid_unpack((struct lu_fid *) rec,
3327                                        (struct osd_fid_pack *)iam_rec);
3328                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
3329                         osd_quota_unpack(obj, rec);
3330         }
3331
3332         iam_it_put(it);
3333         iam_it_fini(it);
3334         osd_ipd_put(env, bag, ipd);
3335
3336         LINVRNT(osd_invariant(obj));
3337
3338         RETURN(rc);
3339 }
3340
3341 static int osd_index_declare_iam_insert(const struct lu_env *env,
3342                                         struct dt_object *dt,
3343                                         const struct dt_rec *rec,
3344                                         const struct dt_key *key,
3345                                         struct thandle *handle)
3346 {
3347         struct osd_thandle *oh;
3348
3349         LASSERT(handle != NULL);
3350
3351         oh = container_of0(handle, struct osd_thandle, ot_super);
3352         LASSERT(oh->ot_handle == NULL);
3353
3354         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3355                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
3356
3357         return 0;
3358 }
3359
3360 /**
3361  *      Inserts (key, value) pair in \a dt index object.
3362  *
3363  *      \param  dt      osd index object
3364  *      \param  key     key for index
3365  *      \param  rec     record reference
3366  *      \param  th      transaction handler
3367  *
3368  *      \retval  0  success
3369  *      \retval -ve failure
3370  */
3371 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
3372                                 const struct dt_rec *rec,
3373                                 const struct dt_key *key, struct thandle *th,
3374                                 struct lustre_capa *capa, int ignore_quota)
3375 {
3376         struct osd_object     *obj = osd_dt_obj(dt);
3377         struct iam_path_descr *ipd;
3378         struct osd_thandle    *oh;
3379         struct iam_container  *bag = &obj->oo_dir->od_container;
3380         struct osd_thread_info *oti = osd_oti_get(env);
3381         struct iam_rec         *iam_rec;
3382         int                     rc;
3383
3384         ENTRY;
3385
3386         LINVRNT(osd_invariant(obj));
3387         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3388         LASSERT(bag->ic_object == obj->oo_inode);
3389         LASSERT(th != NULL);
3390
3391         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3392                 RETURN(-EACCES);
3393
3394         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3395
3396         ipd = osd_idx_ipd_get(env, bag);
3397         if (unlikely(ipd == NULL))
3398                 RETURN(-ENOMEM);
3399
3400         oh = container_of0(th, struct osd_thandle, ot_super);
3401         LASSERT(oh->ot_handle != NULL);
3402         LASSERT(oh->ot_handle->h_transaction != NULL);
3403         if (S_ISDIR(obj->oo_inode->i_mode)) {
3404                 iam_rec = (struct iam_rec *)oti->oti_ldp;
3405                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
3406         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3407                 /* pack quota uid/gid */
3408                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3409                 key = (const struct dt_key *)&oti->oti_quota_id;
3410                 /* pack quota record */
3411                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
3412                 iam_rec = (struct iam_rec *)rec;
3413         } else {
3414                 iam_rec = (struct iam_rec *)rec;
3415         }
3416
3417         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
3418                         iam_rec, ipd);
3419         osd_ipd_put(env, bag, ipd);
3420         LINVRNT(osd_invariant(obj));
3421         RETURN(rc);
3422 }
3423
3424 /**
3425  * Calls ldiskfs_add_entry() to add directory entry
3426  * into the directory. This is required for
3427  * interoperability mode (b11826)
3428  *
3429  * \retval   0, on success
3430  * \retval -ve, on error
3431  */
3432 static int __osd_ea_add_rec(struct osd_thread_info *info,
3433                             struct osd_object *pobj, struct inode  *cinode,
3434                             const char *name, const struct dt_rec *fid,
3435                             struct htree_lock *hlock, struct thandle *th)
3436 {
3437         struct ldiskfs_dentry_param *ldp;
3438         struct dentry               *child;
3439         struct osd_thandle          *oth;
3440         int                          rc;
3441
3442         oth = container_of(th, struct osd_thandle, ot_super);
3443         LASSERT(oth->ot_handle != NULL);
3444         LASSERT(oth->ot_handle->h_transaction != NULL);
3445         LASSERT(pobj->oo_inode);
3446
3447         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3448         if (unlikely(pobj->oo_inode ==
3449                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
3450                 ldp->edp_magic = 0;
3451         else
3452                 osd_get_ldiskfs_dirent_param(ldp, fid);
3453         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
3454         child->d_fsdata = (void *)ldp;
3455         ll_vfs_dq_init(pobj->oo_inode);
3456         rc = osd_ldiskfs_add_entry(oth->ot_handle, child, cinode, hlock);
3457
3458         RETURN(rc);
3459 }
3460
3461 /**
3462  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
3463  * into the directory.Also sets flags into osd object to
3464  * indicate dot and dotdot are created. This is required for
3465  * interoperability mode (b11826)
3466  *
3467  * \param dir   directory for dot and dotdot fixup.
3468  * \param obj   child object for linking
3469  *
3470  * \retval   0, on success
3471  * \retval -ve, on error
3472  */
3473 static int osd_add_dot_dotdot(struct osd_thread_info *info,
3474                               struct osd_object *dir,
3475                               struct inode  *parent_dir, const char *name,
3476                               const struct dt_rec *dot_fid,
3477                               const struct dt_rec *dot_dot_fid,
3478                               struct thandle *th)
3479 {
3480         struct inode                *inode = dir->oo_inode;
3481         struct osd_thandle          *oth;
3482         int result = 0;
3483
3484         oth = container_of(th, struct osd_thandle, ot_super);
3485         LASSERT(oth->ot_handle->h_transaction != NULL);
3486         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
3487
3488         if (strcmp(name, dot) == 0) {
3489                 if (dir->oo_compat_dot_created) {
3490                         result = -EEXIST;
3491                 } else {
3492                         LASSERT(inode == parent_dir);
3493                         dir->oo_compat_dot_created = 1;
3494                         result = 0;
3495                 }
3496         } else if (strcmp(name, dotdot) == 0) {
3497                 if (!dir->oo_compat_dot_created)
3498                         return -EINVAL;
3499                 /* in case of rename, dotdot is already created */
3500                 if (dir->oo_compat_dotdot_created) {
3501                         return __osd_ea_add_rec(info, dir, parent_dir, name,
3502                                                 dot_dot_fid, NULL, th);
3503                 }
3504
3505                 result = osd_add_dot_dotdot_internal(info, dir->oo_inode,
3506                                                 parent_dir, dot_fid,
3507                                                 dot_dot_fid, oth);
3508                 if (result == 0)
3509                         dir->oo_compat_dotdot_created = 1;
3510         }
3511
3512         return result;
3513 }
3514
3515
3516 /**
3517  * It will call the appropriate osd_add* function and return the
3518  * value, return by respective functions.
3519  */
3520 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
3521                           struct inode *cinode, const char *name,
3522                           const struct dt_rec *fid, struct thandle *th)
3523 {
3524         struct osd_thread_info *info   = osd_oti_get(env);
3525         struct htree_lock      *hlock;
3526         int                     rc;
3527
3528         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
3529
3530         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
3531                                                    name[2] =='\0'))) {
3532                 if (hlock != NULL) {
3533                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3534                                            pobj->oo_inode, 0);
3535                 } else {
3536                         down_write(&pobj->oo_ext_idx_sem);
3537                 }
3538                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
3539                      (struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
3540                                         fid, th);
3541         } else {
3542                 if (hlock != NULL) {
3543                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3544                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
3545                 } else {
3546                         down_write(&pobj->oo_ext_idx_sem);
3547                 }
3548
3549                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
3550                         struct lu_fid *tfid = &info->oti_fid;
3551
3552                         *tfid = *(const struct lu_fid *)fid;
3553                         tfid->f_ver = ~0;
3554                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
3555                                               (const struct dt_rec *)tfid,
3556                                               hlock, th);
3557                 } else {
3558                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
3559                                               hlock, th);
3560                 }
3561         }
3562         if (hlock != NULL)
3563                 ldiskfs_htree_unlock(hlock);
3564         else
3565                 up_write(&pobj->oo_ext_idx_sem);
3566
3567         return rc;
3568 }
3569
3570 static void
3571 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
3572                       struct osd_idmap_cache *oic)
3573 {
3574         struct osd_scrub    *scrub = &dev->od_scrub;
3575         struct lu_fid       *fid   = &oic->oic_fid;
3576         struct osd_inode_id *id    = &oti->oti_id;
3577         int                  once  = 0;
3578         int                  rc;
3579         ENTRY;
3580
3581         if (!fid_is_norm(fid) && !fid_is_igif(fid))
3582                 RETURN_EXIT;
3583
3584 again:
3585         rc = osd_oi_lookup(oti, dev, fid, id, true);
3586         if (rc != 0 && rc != -ENOENT)
3587                 RETURN_EXIT;
3588
3589         if (rc == 0 && osd_id_eq(id, &oic->oic_lid))
3590                 RETURN_EXIT;
3591
3592         if (thread_is_running(&scrub->os_thread)) {
3593                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
3594                 /* There is race condition between osd_oi_lookup and OI scrub.
3595                  * The OI scrub finished just after osd_oi_lookup() failure.
3596                  * Under such case, it is unnecessary to trigger OI scrub again,
3597                  * but try to call osd_oi_lookup() again. */
3598                 if (unlikely(rc == -EAGAIN))
3599                         goto again;
3600
3601                 RETURN_EXIT;
3602         }
3603
3604         if (!dev->od_noscrub && ++once == 1) {
3605                 CDEBUG(D_LFSCK, "Trigger OI scrub by RPC for "DFID"\n",
3606                        PFID(fid));
3607                 rc = osd_scrub_start(dev);
3608                 LCONSOLE_ERROR("%.16s: trigger OI scrub by RPC for "DFID
3609                                ", rc = %d [2]\n",
3610                                LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
3611                                PFID(fid), rc);
3612                 if (rc == 0)
3613                         goto again;
3614         }
3615
3616         EXIT;
3617 }
3618
3619 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
3620                                struct osd_device *dev,
3621                                struct osd_idmap_cache *oic,
3622                                struct lu_fid *fid, __u32 ino)
3623 {
3624         struct lustre_mdt_attrs *lma   = &oti->oti_mdt_attrs;
3625         struct inode            *inode;
3626         int                      rc;
3627
3628         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
3629         inode = osd_iget(oti, dev, &oic->oic_lid);
3630         if (IS_ERR(inode)) {
3631                 fid_zero(&oic->oic_fid);
3632                 return PTR_ERR(inode);
3633         }
3634
3635         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, lma);
3636         iput(inode);
3637         if (rc != 0)
3638                 fid_zero(&oic->oic_fid);
3639         else
3640                 *fid = oic->oic_fid = lma->lma_self_fid;
3641         return rc;
3642 }
3643
3644 /**
3645  * Calls ->lookup() to find dentry. From dentry get inode and
3646  * read inode's ea to get fid. This is required for  interoperability
3647  * mode (b11826)
3648  *
3649  * \retval   0, on success
3650  * \retval -ve, on error
3651  */
3652 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
3653                              struct dt_rec *rec, const struct dt_key *key)
3654 {
3655         struct inode               *dir    = obj->oo_inode;
3656         struct dentry              *dentry;
3657         struct ldiskfs_dir_entry_2 *de;
3658         struct buffer_head         *bh;
3659         struct lu_fid              *fid = (struct lu_fid *) rec;
3660         struct htree_lock          *hlock = NULL;
3661         int                         ino;
3662         int                         rc;
3663         ENTRY;
3664
3665         LASSERT(dir->i_op != NULL && dir->i_op->lookup != NULL);
3666
3667         dentry = osd_child_dentry_get(env, obj,
3668                                       (char *)key, strlen((char *)key));
3669
3670         if (obj->oo_hl_head != NULL) {
3671                 hlock = osd_oti_get(env)->oti_hlock;
3672                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3673                                    dir, LDISKFS_HLOCK_LOOKUP);
3674         } else {
3675                 down_read(&obj->oo_ext_idx_sem);
3676         }
3677
3678         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
3679         if (bh) {
3680                 struct osd_thread_info *oti = osd_oti_get(env);
3681                 struct osd_inode_id *id = &oti->oti_id;
3682                 struct osd_idmap_cache *oic = &oti->oti_cache;
3683                 struct osd_device *dev = osd_obj2dev(obj);
3684                 struct osd_scrub *scrub = &dev->od_scrub;
3685                 struct scrub_file *sf = &scrub->os_file;
3686
3687                 ino = le32_to_cpu(de->inode);
3688                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
3689                         brelse(bh);
3690                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
3691                         GOTO(out, rc);
3692                 }
3693
3694                 rc = osd_get_fid_from_dentry(de, rec);
3695
3696                 /* done with de, release bh */
3697                 brelse(bh);
3698                 if (rc != 0)
3699                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
3700                 else
3701                         osd_id_gen(id, ino, OSD_OII_NOGEN);
3702                 if (rc != 0 || osd_remote_fid(env, dev, fid)) {
3703                         fid_zero(&oic->oic_fid);
3704                         GOTO(out, rc);
3705                 }
3706
3707                 oic->oic_lid = *id;
3708                 oic->oic_fid = *fid;
3709                 if ((scrub->os_pos_current <= ino) &&
3710                     ((sf->sf_flags & SF_INCONSISTENT) ||
3711                      (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
3712                      ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
3713                                       sf->sf_oi_bitmap)))
3714                         osd_consistency_check(oti, dev, oic);
3715         } else {
3716                 rc = -ENOENT;
3717         }
3718
3719         GOTO(out, rc);
3720
3721 out:
3722         if (hlock != NULL)
3723                 ldiskfs_htree_unlock(hlock);
3724         else
3725                 up_read(&obj->oo_ext_idx_sem);
3726         return rc;
3727 }
3728
3729 /**
3730  * Find the osd object for given fid.
3731  *
3732  * \param fid need to find the osd object having this fid
3733  *
3734  * \retval osd_object on success
3735  * \retval        -ve on error
3736  */
3737 struct osd_object *osd_object_find(const struct lu_env *env,
3738                                    struct dt_object *dt,
3739                                    const struct lu_fid *fid)
3740 {
3741         struct lu_device  *ludev = dt->do_lu.lo_dev;
3742         struct osd_object *child = NULL;
3743         struct lu_object  *luch;
3744         struct lu_object  *lo;
3745
3746         /*
3747          * at this point topdev might not exist yet
3748          * (i.e. MGS is preparing profiles). so we can
3749          * not rely on topdev and instead lookup with
3750          * our device passed as topdev. this can't work
3751          * if the object isn't cached yet (as osd doesn't
3752          * allocate lu_header). IOW, the object must be
3753          * in the cache, otherwise lu_object_alloc() crashes
3754          * -bzzz
3755          */
3756         luch = lu_object_find_at(env, ludev, fid, NULL);
3757         if (!IS_ERR(luch)) {
3758                 if (lu_object_exists(luch)) {
3759                         lo = lu_object_locate(luch->lo_header, ludev->ld_type);
3760                         if (lo != NULL)
3761                                 child = osd_obj(lo);
3762                         else
3763                                 LU_OBJECT_DEBUG(D_ERROR, env, luch,
3764                                                 "lu_object can't be located"
3765                                                 DFID"\n", PFID(fid));
3766
3767                         if (child == NULL) {
3768                                 lu_object_put(env, luch);
3769                                 CERROR("Unable to get osd_object\n");
3770                                 child = ERR_PTR(-ENOENT);
3771                         }
3772                 } else {
3773                         LU_OBJECT_DEBUG(D_ERROR, env, luch,
3774                                         "lu_object does not exists "DFID"\n",
3775                                         PFID(fid));
3776                         lu_object_put(env, luch);
3777                         child = ERR_PTR(-ENOENT);
3778                 }
3779         } else
3780                 child = (void *)luch;
3781
3782         return child;
3783 }
3784
3785 /**
3786  * Put the osd object once done with it.
3787  *
3788  * \param obj osd object that needs to be put
3789  */
3790 static inline void osd_object_put(const struct lu_env *env,
3791                                   struct osd_object *obj)
3792 {
3793         lu_object_put(env, &obj->oo_dt.do_lu);
3794 }
3795
3796 static int osd_index_declare_ea_insert(const struct lu_env *env,
3797                                        struct dt_object *dt,
3798                                        const struct dt_rec *rec,
3799                                        const struct dt_key *key,
3800                                        struct thandle *handle)
3801 {
3802         struct osd_thandle      *oh;
3803         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
3804         struct lu_fid           *fid = (struct lu_fid *)rec;
3805         int                     rc;
3806         ENTRY;
3807
3808         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3809         LASSERT(handle != NULL);
3810
3811         oh = container_of0(handle, struct osd_thandle, ot_super);
3812         LASSERT(oh->ot_handle == NULL);
3813
3814         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3815                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
3816
3817         if (osd_dt_obj(dt)->oo_inode == NULL) {
3818                 const char *name  = (const char *)key;
3819                 /* Object is not being created yet. Only happens when
3820                  *     1. declare directory create
3821                  *     2. declare insert .
3822                  *     3. declare insert ..
3823                  */
3824                 LASSERT(strcmp(name, dotdot) == 0 || strcmp(name, dot) == 0);
3825         } else {
3826                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
3827
3828                 /* We ignore block quota on meta pool (MDTs), so needn't
3829                  * calculate how many blocks will be consumed by this index
3830                  * insert */
3831                 rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0,
3832                                            oh, true, true, NULL, false);
3833         }
3834
3835         if (fid == NULL)
3836                 RETURN(0);
3837
3838         rc = osd_remote_fid(env, osd, fid);
3839         if (rc <= 0)
3840                 RETURN(rc);
3841
3842         rc = 0;
3843
3844         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
3845                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
3846         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3847                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3848         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3849                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3850
3851         RETURN(rc);
3852 }
3853
3854 /**
3855  * Index add function for interoperability mode (b11826).
3856  * It will add the directory entry.This entry is needed to
3857  * maintain name->fid mapping.
3858  *
3859  * \param key it is key i.e. file entry to be inserted
3860  * \param rec it is value of given key i.e. fid
3861  *
3862  * \retval   0, on success
3863  * \retval -ve, on error
3864  */
3865 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
3866                                const struct dt_rec *rec,
3867                                const struct dt_key *key, struct thandle *th,
3868                                struct lustre_capa *capa, int ignore_quota)
3869 {
3870         struct osd_object       *obj = osd_dt_obj(dt);
3871         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
3872         struct lu_fid           *fid = (struct lu_fid *) rec;
3873         const char              *name = (const char *)key;
3874         struct osd_thread_info  *oti   = osd_oti_get(env);
3875         struct osd_inode_id     *id    = &oti->oti_id;
3876         struct inode            *child_inode = NULL;
3877         struct osd_object       *child = NULL;
3878         int                     rc;
3879         ENTRY;
3880
3881         LASSERT(osd_invariant(obj));
3882         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3883         LASSERT(th != NULL);
3884
3885         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3886
3887         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3888                 RETURN(-EACCES);
3889
3890         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!", PFID(fid));
3891
3892         rc = osd_remote_fid(env, osd, fid);
3893         if (rc < 0) {
3894                 CERROR("%s: Can not find object "DFID" rc %d\n",
3895                        osd_name(osd), PFID(fid), rc);
3896                 RETURN(rc);
3897         }
3898
3899         if (rc == 1) {
3900                 /* Insert remote entry */
3901                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
3902                         struct osd_mdobj_map    *omm = osd->od_mdt_map;
3903                         struct osd_thandle      *oh;
3904
3905                         /* If parent on remote MDT, we need put this object
3906                          * under AGENT */
3907                         oh = container_of(th, typeof(*oh), ot_super);
3908                         rc = osd_add_to_agent(env, osd, obj, oh);
3909                         if (rc != 0) {
3910                                 CERROR("%s: add agent "DFID" error: rc = %d\n",
3911                                        osd_name(osd),
3912                                        PFID(lu_object_fid(&dt->do_lu)), rc);
3913                                 RETURN(rc);
3914                         }
3915
3916                         child_inode = igrab(omm->omm_agent_dentry->d_inode);
3917                 } else {
3918                         child_inode = osd_create_remote_inode(env, osd, obj,
3919                                                               fid, th);
3920                         if (IS_ERR(child_inode))
3921                                 RETURN(PTR_ERR(child_inode));
3922                 }
3923         } else {
3924                 /* Insert local entry */
3925                 child = osd_object_find(env, dt, fid);
3926                 if (IS_ERR(child)) {
3927                         CERROR("%s: Can not find object "DFID"%u:%u: rc = %d\n",
3928                                osd_name(osd), PFID(fid),
3929                                id->oii_ino, id->oii_gen,
3930                                (int)PTR_ERR(child_inode));
3931                         RETURN(PTR_ERR(child_inode));
3932                 }
3933                 child_inode = igrab(child->oo_inode);
3934         }
3935
3936         rc = osd_ea_add_rec(env, obj, child_inode, name, rec, th);
3937
3938         iput(child_inode);
3939         if (child != NULL)
3940                 osd_object_put(env, child);
3941         LASSERT(osd_invariant(obj));
3942         RETURN(rc);
3943 }
3944
3945 /**
3946  *  Initialize osd Iterator for given osd index object.
3947  *
3948  *  \param  dt      osd index object
3949  */
3950
3951 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
3952                                      struct dt_object *dt,
3953                                      __u32 unused,
3954                                      struct lustre_capa *capa)
3955 {
3956         struct osd_it_iam      *it;
3957         struct osd_thread_info *oti = osd_oti_get(env);
3958         struct osd_object      *obj = osd_dt_obj(dt);
3959         struct lu_object       *lo  = &dt->do_lu;
3960         struct iam_path_descr  *ipd;
3961         struct iam_container   *bag = &obj->oo_dir->od_container;
3962
3963         LASSERT(lu_object_exists(lo));
3964
3965         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
3966                 return ERR_PTR(-EACCES);
3967
3968         it = &oti->oti_it;
3969         ipd = osd_it_ipd_get(env, bag);
3970         if (likely(ipd != NULL)) {
3971                 it->oi_obj = obj;
3972                 it->oi_ipd = ipd;
3973                 lu_object_get(lo);
3974                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
3975                 return (struct dt_it *)it;
3976         }
3977         return ERR_PTR(-ENOMEM);
3978 }
3979
3980 /**
3981  * free given Iterator.
3982  */
3983
3984 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
3985 {
3986         struct osd_it_iam *it = (struct osd_it_iam *)di;
3987         struct osd_object *obj = it->oi_obj;
3988
3989         iam_it_fini(&it->oi_it);
3990         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
3991         lu_object_put(env, &obj->oo_dt.do_lu);
3992 }
3993
3994 /**
3995  *  Move Iterator to record specified by \a key
3996  *
3997  *  \param  di      osd iterator
3998  *  \param  key     key for index
3999  *
4000  *  \retval +ve  di points to record with least key not larger than key
4001  *  \retval  0   di points to exact matched key
4002  *  \retval -ve  failure
4003  */
4004
4005 static int osd_it_iam_get(const struct lu_env *env,
4006                           struct dt_it *di, const struct dt_key *key)
4007 {
4008         struct osd_thread_info  *oti = osd_oti_get(env);
4009         struct osd_it_iam       *it = (struct osd_it_iam *)di;
4010
4011         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4012                 /* swab quota uid/gid */
4013                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4014                 key = (struct dt_key *)&oti->oti_quota_id;
4015         }
4016
4017         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
4018 }
4019
4020 /**
4021  *  Release Iterator
4022  *
4023  *  \param  di      osd iterator
4024  */
4025 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
4026 {
4027         struct osd_it_iam *it = (struct osd_it_iam *)di;
4028
4029         iam_it_put(&it->oi_it);
4030 }
4031
4032 /**
4033  *  Move iterator by one record
4034  *
4035  *  \param  di      osd iterator
4036  *
4037  *  \retval +1   end of container reached
4038  *  \retval  0   success
4039  *  \retval -ve  failure
4040  */
4041
4042 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
4043 {
4044         struct osd_it_iam *it = (struct osd_it_iam *)di;
4045
4046         return iam_it_next(&it->oi_it);
4047 }
4048
4049 /**
4050  * Return pointer to the key under iterator.
4051  */
4052
4053 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
4054                                  const struct dt_it *di)
4055 {
4056         struct osd_thread_info *oti = osd_oti_get(env);
4057         struct osd_it_iam      *it = (struct osd_it_iam *)di;
4058         struct osd_object      *obj = it->oi_obj;
4059         struct dt_key          *key;
4060
4061         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
4062
4063         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
4064                 /* swab quota uid/gid */
4065                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
4066                 key = (struct dt_key *)&oti->oti_quota_id;
4067         }
4068
4069         return key;
4070 }
4071
4072 /**
4073  * Return size of key under iterator (in bytes)
4074  */
4075
4076 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
4077 {
4078         struct osd_it_iam *it = (struct osd_it_iam *)di;
4079
4080         return iam_it_key_size(&it->oi_it);
4081 }
4082
4083 static inline void
4084 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
4085 {
4086         /* check if file type is required */
4087         if (ent->lde_attrs & LUDA_TYPE) {
4088                 int align = sizeof(struct luda_type) - 1;
4089                 struct luda_type *lt;
4090
4091                 len = (len + align) & ~align;
4092                 lt = (struct luda_type *)(ent->lde_name + len);
4093                 lt->lt_type = cpu_to_le16(CFS_DTTOIF(type));
4094         }
4095
4096         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
4097 }
4098
4099 /**
4100  * build lu direct from backend fs dirent.
4101  */
4102
4103 static inline void
4104 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
4105                    char *name, __u16 namelen, __u16 type, __u32 attr)
4106 {
4107         ent->lde_attrs = attr | LUDA_FID;
4108         fid_cpu_to_le(&ent->lde_fid, fid);
4109
4110         ent->lde_hash = cpu_to_le64(offset);
4111         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
4112
4113         strncpy(ent->lde_name, name, namelen);
4114         ent->lde_namelen = cpu_to_le16(namelen);
4115
4116         /* append lustre attributes */
4117         osd_it_append_attrs(ent, namelen, type);
4118 }
4119
4120 /**
4121  * Return pointer to the record under iterator.
4122  */
4123 static int osd_it_iam_rec(const struct lu_env *env,
4124                           const struct dt_it *di,
4125                           struct dt_rec *dtrec, __u32 attr)
4126 {
4127         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
4128         struct osd_thread_info *info = osd_oti_get(env);
4129         ENTRY;
4130
4131         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
4132                 const struct osd_fid_pack *rec;
4133                 struct lu_fid             *fid = &info->oti_fid;
4134                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
4135                 char                      *name;
4136                 int                        namelen;
4137                 __u64                      hash;
4138                 int                        rc;
4139
4140                 name = (char *)iam_it_key_get(&it->oi_it);
4141                 if (IS_ERR(name))
4142                         RETURN(PTR_ERR(name));
4143
4144                 namelen = iam_it_key_size(&it->oi_it);
4145
4146                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
4147                 if (IS_ERR(rec))
4148                         RETURN(PTR_ERR(rec));
4149
4150                 rc = osd_fid_unpack(fid, rec);
4151                 if (rc)
4152                         RETURN(rc);
4153
4154                 hash = iam_it_store(&it->oi_it);
4155
4156                 /* IAM does not store object type in IAM index (dir) */
4157                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
4158                                    0, LUDA_FID);
4159         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4160                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4161                            (struct iam_rec *)dtrec);
4162                 osd_quota_unpack(it->oi_obj, dtrec);
4163         } else {
4164                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4165                            (struct iam_rec *)dtrec);
4166         }
4167
4168         RETURN(0);
4169 }
4170
4171 /**
4172  * Returns cookie for current Iterator position.
4173  */
4174 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
4175 {
4176         struct osd_it_iam *it = (struct osd_it_iam *)di;
4177
4178         return iam_it_store(&it->oi_it);
4179 }
4180
4181 /**
4182  * Restore iterator from cookie.
4183  *
4184  * \param  di      osd iterator
4185  * \param  hash    Iterator location cookie
4186  *
4187  * \retval +ve  di points to record with least key not larger than key.
4188  * \retval  0   di points to exact matched key
4189  * \retval -ve  failure
4190  */
4191
4192 static int osd_it_iam_load(const struct lu_env *env,
4193                            const struct dt_it *di, __u64 hash)
4194 {
4195         struct osd_it_iam *it = (struct osd_it_iam *)di;
4196
4197         return iam_it_load(&it->oi_it, hash);
4198 }
4199
4200 static const struct dt_index_operations osd_index_iam_ops = {
4201         .dio_lookup         = osd_index_iam_lookup,
4202         .dio_declare_insert = osd_index_declare_iam_insert,
4203         .dio_insert         = osd_index_iam_insert,
4204         .dio_declare_delete = osd_index_declare_iam_delete,
4205         .dio_delete         = osd_index_iam_delete,
4206         .dio_it     = {
4207                 .init     = osd_it_iam_init,
4208                 .fini     = osd_it_iam_fini,
4209                 .get      = osd_it_iam_get,
4210                 .put      = osd_it_iam_put,
4211                 .next     = osd_it_iam_next,
4212                 .key      = osd_it_iam_key,
4213                 .key_size = osd_it_iam_key_size,
4214                 .rec      = osd_it_iam_rec,
4215                 .store    = osd_it_iam_store,
4216                 .load     = osd_it_iam_load
4217         }
4218 };
4219
4220
4221 /**
4222  * Creates or initializes iterator context.
4223  *
4224  * \retval struct osd_it_ea, iterator structure on success
4225  *
4226  */
4227 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
4228                                     struct dt_object *dt,
4229                                     __u32 attr,
4230                                     struct lustre_capa *capa)
4231 {
4232         struct osd_object       *obj  = osd_dt_obj(dt);
4233         struct osd_thread_info  *info = osd_oti_get(env);
4234         struct osd_it_ea        *it   = &info->oti_it_ea;
4235         struct lu_object        *lo   = &dt->do_lu;
4236         struct dentry           *obj_dentry = &info->oti_it_dentry;
4237         ENTRY;
4238         LASSERT(lu_object_exists(lo));
4239
4240         obj_dentry->d_inode = obj->oo_inode;
4241         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
4242         obj_dentry->d_name.hash = 0;
4243
4244         it->oie_rd_dirent       = 0;
4245         it->oie_it_dirent       = 0;
4246         it->oie_dirent          = NULL;
4247         it->oie_buf             = info->oti_it_ea_buf;
4248         it->oie_obj             = obj;
4249         it->oie_file.f_pos      = 0;
4250         it->oie_file.f_dentry   = obj_dentry;
4251         if (attr & LUDA_64BITHASH)
4252                 it->oie_file.f_mode |= FMODE_64BITHASH;
4253         else
4254                 it->oie_file.f_mode |= FMODE_32BITHASH;
4255         it->oie_file.f_mapping    = obj->oo_inode->i_mapping;
4256         it->oie_file.f_op         = obj->oo_inode->i_fop;
4257         it->oie_file.private_data = NULL;
4258         lu_object_get(lo);
4259         RETURN((struct dt_it *) it);
4260 }
4261
4262 /**
4263  * Destroy or finishes iterator context.
4264  *
4265  * \param di iterator structure to be destroyed
4266  */
4267 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
4268 {
4269         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4270         struct osd_object    *obj  = it->oie_obj;
4271         struct inode       *inode  = obj->oo_inode;
4272
4273         ENTRY;
4274         it->oie_file.f_op->release(inode, &it->oie_file);
4275         lu_object_put(env, &obj->oo_dt.do_lu);
4276         EXIT;
4277 }
4278
4279 /**
4280  * It position the iterator at given key, so that next lookup continues from
4281  * that key Or it is similar to dio_it->load() but based on a key,
4282  * rather than file position.
4283  *
4284  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
4285  * to the beginning.
4286  *
4287  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
4288  */
4289 static int osd_it_ea_get(const struct lu_env *env,
4290                          struct dt_it *di, const struct dt_key *key)
4291 {
4292         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4293
4294         ENTRY;
4295         LASSERT(((const char *)key)[0] == '\0');
4296         it->oie_file.f_pos      = 0;
4297         it->oie_rd_dirent       = 0;
4298         it->oie_it_dirent       = 0;
4299         it->oie_dirent          = NULL;
4300
4301         RETURN(+1);
4302 }
4303
4304 /**
4305  * Does nothing
4306  */
4307 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
4308 {
4309 }
4310
4311 /**
4312  * It is called internally by ->readdir(). It fills the
4313  * iterator's in-memory data structure with required
4314  * information i.e. name, namelen, rec_size etc.
4315  *
4316  * \param buf in which information to be filled in.
4317  * \param name name of the file in given dir
4318  *
4319  * \retval 0 on success
4320  * \retval 1 on buffer full
4321  */
4322 static int osd_ldiskfs_filldir(char *buf, const char *name, int namelen,
4323                                loff_t offset, __u64 ino,
4324                                unsigned d_type)
4325 {
4326         struct osd_it_ea        *it   = (struct osd_it_ea *)buf;
4327         struct osd_object       *obj  = it->oie_obj;
4328         struct osd_it_ea_dirent *ent  = it->oie_dirent;
4329         struct lu_fid           *fid  = &ent->oied_fid;
4330         struct osd_fid_pack     *rec;
4331         ENTRY;
4332
4333         /* this should never happen */
4334         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
4335                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
4336                 RETURN(-EIO);
4337         }
4338
4339         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
4340             OSD_IT_EA_BUFSIZE)
4341                 RETURN(1);
4342
4343         /* "." is just the object itself. */
4344         if (namelen == 1 && name[0] == '.') {
4345                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4346         } else if (d_type & LDISKFS_DIRENT_LUFID) {
4347                 rec = (struct osd_fid_pack*) (name + namelen + 1);
4348                 if (osd_fid_unpack(fid, rec) != 0)
4349                         fid_zero(fid);
4350         } else {
4351                 fid_zero(fid);
4352         }
4353         d_type &= ~LDISKFS_DIRENT_LUFID;
4354
4355         /* NOT export local root. */
4356         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
4357                 ino = obj->oo_inode->i_ino;
4358                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4359         }
4360
4361         ent->oied_ino     = ino;
4362         ent->oied_off     = offset;
4363         ent->oied_namelen = namelen;
4364         ent->oied_type    = d_type;
4365
4366         memcpy(ent->oied_name, name, namelen);
4367
4368         it->oie_rd_dirent++;
4369         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
4370         RETURN(0);
4371 }
4372
4373 /**
4374  * Calls ->readdir() to load a directory entry at a time
4375  * and stored it in iterator's in-memory data structure.
4376  *
4377  * \param di iterator's in memory structure
4378  *
4379  * \retval   0 on success
4380  * \retval -ve on error
4381  */
4382 static int osd_ldiskfs_it_fill(const struct lu_env *env,
4383                                const struct dt_it *di)
4384 {
4385         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
4386         struct osd_object  *obj   = it->oie_obj;
4387         struct inode       *inode = obj->oo_inode;
4388         struct htree_lock  *hlock = NULL;
4389         int                 result = 0;
4390
4391         ENTRY;
4392         it->oie_dirent = it->oie_buf;
4393         it->oie_rd_dirent = 0;
4394
4395         if (obj->oo_hl_head != NULL) {
4396                 hlock = osd_oti_get(env)->oti_hlock;
4397                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4398                                    inode, LDISKFS_HLOCK_READDIR);
4399         } else {
4400                 down_read(&obj->oo_ext_idx_sem);
4401         }
4402
4403         result = inode->i_fop->readdir(&it->oie_file, it,
4404                                        (filldir_t) osd_ldiskfs_filldir);
4405
4406         if (hlock != NULL)
4407                 ldiskfs_htree_unlock(hlock);
4408         else
4409                 up_read(&obj->oo_ext_idx_sem);
4410
4411         if (it->oie_rd_dirent == 0) {
4412                 result = -EIO;
4413         } else {
4414                 it->oie_dirent = it->oie_buf;
4415                 it->oie_it_dirent = 1;
4416         }
4417
4418         RETURN(result);
4419 }
4420
4421 /**
4422  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4423  * to load a directory entry at a time and stored it in
4424  * iterator's in-memory data structure.
4425  *
4426  * \param di iterator's in memory structure
4427  *
4428  * \retval +ve iterator reached to end
4429  * \retval   0 iterator not reached to end
4430  * \retval -ve on error
4431  */
4432 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
4433 {
4434         struct osd_it_ea *it = (struct osd_it_ea *)di;
4435         int rc;
4436
4437         ENTRY;
4438
4439         if (it->oie_it_dirent < it->oie_rd_dirent) {
4440                 it->oie_dirent =
4441                         (void *) it->oie_dirent +
4442                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
4443                                        it->oie_dirent->oied_namelen);
4444                 it->oie_it_dirent++;
4445                 RETURN(0);
4446         } else {
4447                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
4448                         rc = +1;
4449                 else
4450                         rc = osd_ldiskfs_it_fill(env, di);
4451         }
4452
4453         RETURN(rc);
4454 }
4455
4456 /**
4457  * Returns the key at current position from iterator's in memory structure.
4458  *
4459  * \param di iterator's in memory structure
4460  *
4461  * \retval key i.e. struct dt_key on success
4462  */
4463 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
4464                                     const struct dt_it *di)
4465 {
4466         struct osd_it_ea *it = (struct osd_it_ea *)di;
4467
4468         return (struct dt_key *)it->oie_dirent->oied_name;
4469 }
4470
4471 /**
4472  * Returns the key's size at current position from iterator's in memory structure.
4473  *
4474  * \param di iterator's in memory structure
4475  *
4476  * \retval key_size i.e. struct dt_key on success
4477  */
4478 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
4479 {
4480         struct osd_it_ea *it = (struct osd_it_ea *)di;
4481
4482         return it->oie_dirent->oied_namelen;
4483 }
4484
4485 static int
4486 osd_dirent_update(handle_t *jh, struct super_block *sb,
4487                   struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4488                   struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de)
4489 {
4490         struct osd_fid_pack *rec;
4491         int                  rc;
4492         ENTRY;
4493
4494         LASSERT(de->file_type & LDISKFS_DIRENT_LUFID);
4495         LASSERT(de->rec_len >= de->name_len + sizeof(struct osd_fid_pack));
4496
4497         rc = ldiskfs_journal_get_write_access(jh, bh);
4498         if (rc != 0) {
4499                 CERROR("%.16s: fail to write access for update dirent: "
4500                        "name = %.*s, rc = %d\n",
4501                        LDISKFS_SB(sb)->s_es->s_volume_name,
4502                        ent->oied_namelen, ent->oied_name, rc);
4503                 RETURN(rc);
4504         }
4505
4506         rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4507         fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4508         rc = ldiskfs_journal_dirty_metadata(jh, bh);
4509         if (rc != 0)
4510                 CERROR("%.16s: fail to dirty metadata for update dirent: "
4511                        "name = %.*s, rc = %d\n",
4512                        LDISKFS_SB(sb)->s_es->s_volume_name,
4513                        ent->oied_namelen, ent->oied_name, rc);
4514
4515         RETURN(rc);
4516 }
4517
4518 static inline int
4519 osd_dirent_has_space(__u16 reclen, __u16 namelen, unsigned blocksize)
4520 {
4521         if (ldiskfs_rec_len_from_disk(reclen, blocksize) >=
4522             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
4523                 return 1;
4524         else
4525                 return 0;
4526 }
4527
4528 static int
4529 osd_dirent_reinsert(const struct lu_env *env, handle_t *jh,
4530                     struct inode *dir, struct inode *inode,
4531                     struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4532                     struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de,
4533                     struct htree_lock *hlock)
4534 {
4535         struct dentry               *dentry;
4536         struct osd_fid_pack         *rec;
4537         struct ldiskfs_dentry_param *ldp;
4538         int                          rc;
4539         ENTRY;
4540
4541         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
4542                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
4543                 RETURN(0);
4544
4545         /* There is enough space to hold the FID-in-dirent. */
4546         if (osd_dirent_has_space(de->rec_len, ent->oied_namelen,
4547                                  dir->i_sb->s_blocksize)) {
4548                 rc = ldiskfs_journal_get_write_access(jh, bh);
4549                 if (rc != 0) {
4550                         CERROR("%.16s: fail to write access for reinsert "
4551                                "dirent: name = %.*s, rc = %d\n",
4552                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4553                                ent->oied_namelen, ent->oied_name, rc);
4554                         RETURN(rc);
4555                 }
4556
4557                 de->name[de->name_len] = 0;
4558                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4559                 rec->fp_len = sizeof(struct lu_fid) + 1;
4560                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4561                 de->file_type |= LDISKFS_DIRENT_LUFID;
4562
4563                 rc = ldiskfs_journal_dirty_metadata(jh, bh);
4564                 if (rc != 0)
4565                         CERROR("%.16s: fail to dirty metadata for reinsert "
4566                                "dirent: name = %.*s, rc = %d\n",
4567                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4568                                ent->oied_namelen, ent->oied_name, rc);
4569
4570                 RETURN(rc);
4571         }
4572
4573         rc = ldiskfs_delete_entry(jh, dir, de, bh);
4574         if (rc != 0) {
4575                 CERROR("%.16s: fail to delete entry for reinsert dirent: "
4576                        "name = %.*s, rc = %d\n",
4577                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4578                        ent->oied_namelen, ent->oied_name, rc);
4579                 RETURN(rc);
4580         }
4581
4582         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
4583                                            ent->oied_namelen);
4584         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
4585         osd_get_ldiskfs_dirent_param(ldp, (const struct dt_rec *)fid);
4586         dentry->d_fsdata = (void *)ldp;
4587         ll_vfs_dq_init(dir);
4588         rc = osd_ldiskfs_add_entry(jh, dentry, inode, hlock);
4589         /* It is too bad, we cannot reinsert the name entry back.
4590          * That means we lose it! */
4591         if (rc != 0)
4592                 CERROR("%.16s: fail to insert entry for reinsert dirent: "
4593                        "name = %.*s, rc = %d\n",
4594                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4595                        ent->oied_namelen, ent->oied_name, rc);
4596
4597         RETURN(rc);
4598 }
4599
4600 static int
4601 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
4602                         struct osd_it_ea *it, struct lu_fid *fid,
4603                         struct osd_inode_id *id, __u32 *attr)
4604 {
4605         struct osd_thread_info     *info        = osd_oti_get(env);
4606         struct lustre_mdt_attrs    *lma         = &info->oti_mdt_attrs;
4607         struct osd_device          *dev         = osd_obj2dev(obj);
4608         struct super_block         *sb          = osd_sb(dev);
4609         const char                 *devname     =
4610                                         LDISKFS_SB(sb)->s_es->s_volume_name;
4611         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
4612         struct inode               *dir         = obj->oo_inode;
4613         struct htree_lock          *hlock       = NULL;
4614         struct buffer_head         *bh          = NULL;
4615         handle_t                   *jh          = NULL;
4616         struct ldiskfs_dir_entry_2 *de;
4617         struct dentry              *dentry;
4618         struct inode               *inode;
4619         int                         credits;
4620         int                         rc;
4621         bool                        dirty       = false;
4622         bool                        is_dotdot   = false;
4623         ENTRY;
4624
4625         if (ent->oied_name[0] == '.') {
4626                 /* Skip dot entry, even if it has stale FID-in-dirent, because
4627                  * we do not use such FID-in-dirent anymore, it is harmless. */
4628                 if (ent->oied_namelen == 1)
4629                         RETURN(0);
4630
4631                 if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
4632                         is_dotdot = true;
4633         }
4634
4635         dentry = osd_child_dentry_get(env, obj, ent->oied_name,
4636                                       ent->oied_namelen);
4637
4638         /* We need to ensure that the name entry is still valid.
4639          * Because it may be removed or renamed by other already.
4640          *
4641          * The unlink or rename operation will start journal before PDO lock,
4642          * so to avoid deadlock, here we need to start journal handle before
4643          * related PDO lock also. But because we do not know whether there
4644          * will be something to be repaired before PDO lock, we just start
4645          * journal without conditions.
4646          *
4647          * We may need to remove the name entry firstly, then insert back.
4648          * One credit is for user quota file update.
4649          * One credit is for group quota file update.
4650          * Two credits are for dirty inode. */
4651         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
4652                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
4653
4654 again:
4655         if (dev->od_dirent_journal) {
4656                 jh = ldiskfs_journal_start_sb(sb, credits);
4657                 if (IS_ERR(jh)) {
4658                         rc = PTR_ERR(jh);
4659                         CERROR("%.16s: fail to start trans for dirent "
4660                                "check_repair: credits %d, name %.*s, rc %d\n",
4661                                devname, credits, ent->oied_namelen,
4662                                ent->oied_name, rc);
4663                         RETURN(rc);
4664                 }
4665         }
4666
4667         if (obj->oo_hl_head != NULL) {
4668                 hlock = osd_oti_get(env)->oti_hlock;
4669                 ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
4670                                    LDISKFS_HLOCK_DEL);
4671         } else {
4672                 down_write(&obj->oo_ext_idx_sem);
4673         }
4674
4675         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
4676         /* For dotdot entry, if there is not enough space to hold FID-in-dirent,
4677          * just keep it there. It only happens when the device upgraded from 1.8
4678          * or restored from MDT file-level backup. For the whole directory, only
4679          * dotdot entry has no FID-in-dirent and needs to get FID from LMA when
4680          * readdir, it will not affect the performance much. */
4681         if ((bh == NULL) || (le32_to_cpu(de->inode) != ent->oied_ino) ||
4682             (is_dotdot && !osd_dirent_has_space(de->rec_len,
4683                                                 ent->oied_namelen,
4684                                                 sb->s_blocksize))) {
4685                 *attr |= LUDA_IGNORE;
4686                 GOTO(out_journal, rc = 0);
4687         }
4688
4689         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
4690         inode = osd_iget(info, dev, id);
4691         if (IS_ERR(inode)) {
4692                 rc = PTR_ERR(inode);
4693                 if (rc == -ENOENT || rc == -ESTALE) {
4694                         *attr |= LUDA_IGNORE;
4695                         rc = 0;
4696                 }
4697
4698                 GOTO(out_journal, rc);
4699         }
4700
4701         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
4702         if (rc == 0) {
4703                 if (fid_is_sane(fid)) {
4704                         /* FID-in-dirent is valid. */
4705                         if (lu_fid_eq(fid, &lma->lma_self_fid))
4706                                 GOTO(out_inode, rc = 0);
4707
4708                         /* Do not repair under dryrun mode. */
4709                         if (*attr & LUDA_VERIFY_DRYRUN) {
4710                                 *attr |= LUDA_REPAIR;
4711                                 GOTO(out_inode, rc = 0);
4712                         }
4713
4714                         if (!dev->od_dirent_journal) {
4715                                 iput(inode);
4716                                 brelse(bh);
4717                                 if (hlock != NULL)
4718                                         ldiskfs_htree_unlock(hlock);
4719                                 else
4720                                         up_write(&obj->oo_ext_idx_sem);
4721                                 dev->od_dirent_journal = 1;
4722                                 goto again;
4723                         }
4724
4725                         *fid = lma->lma_self_fid;
4726                         dirty = true;
4727                         /* Update the FID-in-dirent. */
4728                         rc = osd_dirent_update(jh, sb, ent, fid, bh, de);
4729                         if (rc == 0)
4730                                 *attr |= LUDA_REPAIR;
4731                 } else {
4732                         /* Do not repair under dryrun mode. */
4733                         if (*attr & LUDA_VERIFY_DRYRUN) {
4734                                 *attr |= LUDA_REPAIR;
4735                                 GOTO(out_inode, rc = 0);
4736                         }
4737
4738                         if (!dev->od_dirent_journal) {
4739                                 iput(inode);
4740                                 brelse(bh);
4741                                 if (hlock != NULL)
4742                                         ldiskfs_htree_unlock(hlock);
4743                                 else
4744                                         up_write(&obj->oo_ext_idx_sem);
4745                                 dev->od_dirent_journal = 1;
4746                                 goto again;
4747                         }
4748
4749                         *fid = lma->lma_self_fid;
4750                         dirty = true;
4751                         /* Append the FID-in-dirent. */
4752                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
4753                                                  fid, bh, de, hlock);
4754                         if (rc == 0)
4755                                 *attr |= LUDA_REPAIR;
4756                 }
4757         } else if (rc == -ENODATA) {
4758                 /* Do not repair under dryrun mode. */
4759                 if (*attr & LUDA_VERIFY_DRYRUN) {
4760                         if (fid_is_sane(fid))
4761                                 *attr |= LUDA_REPAIR;
4762                         else
4763                                 *attr |= LUDA_UPGRADE;
4764                         GOTO(out_inode, rc = 0);
4765                 }
4766
4767                 if (!dev->od_dirent_journal) {
4768                         iput(inode);
4769                         brelse(bh);
4770                         if (hlock != NULL)
4771                                 ldiskfs_htree_unlock(hlock);
4772                         else
4773                                 up_write(&obj->oo_ext_idx_sem);
4774                         dev->od_dirent_journal = 1;
4775                         goto again;
4776                 }
4777
4778                 dirty = true;
4779                 if (unlikely(fid_is_sane(fid))) {
4780                         /* FID-in-dirent exists, but FID-in-LMA is lost.
4781                          * Trust the FID-in-dirent, and add FID-in-LMA. */
4782                         rc = osd_ea_fid_set(info, inode, fid);
4783                         if (rc == 0)
4784                                 *attr |= LUDA_REPAIR;
4785                 } else {
4786                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
4787                         /* It is probably IGIF object. Only aappend the
4788                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
4789                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
4790                                                  fid, bh, de, hlock);
4791                         if (rc == 0)
4792                                 *attr |= LUDA_UPGRADE;
4793                 }
4794         }
4795
4796         GOTO(out_inode, rc);
4797
4798 out_inode:
4799         iput(inode);
4800
4801 out_journal:
4802         brelse(bh);
4803         if (hlock != NULL)
4804                 ldiskfs_htree_unlock(hlock);
4805         else
4806                 up_write(&obj->oo_ext_idx_sem);
4807         if (jh != NULL)
4808                 ldiskfs_journal_stop(jh);
4809         if (rc >= 0 && !dirty)
4810                 dev->od_dirent_journal = 0;
4811         return rc;
4812 }
4813
4814 /**
4815  * Returns the value at current position from iterator's in memory structure.
4816  *
4817  * \param di struct osd_it_ea, iterator's in memory structure
4818  * \param attr attr requested for dirent.
4819  * \param lde lustre dirent
4820  *
4821  * \retval   0 no error and \param lde has correct lustre dirent.
4822  * \retval -ve on error
4823  */
4824 static inline int osd_it_ea_rec(const struct lu_env *env,
4825                                 const struct dt_it *di,
4826                                 struct dt_rec *dtrec, __u32 attr)
4827 {
4828         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
4829         struct osd_object      *obj   = it->oie_obj;
4830         struct osd_device      *dev   = osd_obj2dev(obj);
4831         struct osd_scrub       *scrub = &dev->od_scrub;
4832         struct scrub_file      *sf    = &scrub->os_file;
4833         struct osd_thread_info *oti   = osd_oti_get(env);
4834         struct osd_inode_id    *id    = &oti->oti_id;
4835         struct osd_idmap_cache *oic   = &oti->oti_cache;
4836         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
4837         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
4838         __u32                   ino   = it->oie_dirent->oied_ino;
4839         int                     rc    = 0;
4840         ENTRY;
4841
4842         if (attr & LUDA_VERIFY) {
4843                 attr |= LUDA_TYPE;
4844                 if (unlikely(ino == osd_sb(dev)->s_root->d_inode->i_ino)) {
4845                         attr |= LUDA_IGNORE;
4846                         rc = 0;
4847                         goto pack;
4848                 }
4849
4850                 rc = osd_dirent_check_repair(env, obj, it, fid, id, &attr);
4851         } else {
4852                 attr &= ~LU_DIRENT_ATTRS_MASK;
4853                 if (!fid_is_sane(fid)) {
4854                         if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
4855                                 RETURN(-ENOENT);
4856
4857                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
4858                 } else {
4859                         osd_id_gen(id, ino, OSD_OII_NOGEN);
4860                 }
4861         }
4862
4863         if (rc < 0)
4864                 RETURN(rc);
4865
4866 pack:
4867         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
4868                            it->oie_dirent->oied_name,
4869                            it->oie_dirent->oied_namelen,
4870                            it->oie_dirent->oied_type, attr);
4871
4872         if (osd_remote_fid(env, dev, fid))
4873                 RETURN(0);
4874
4875         if (likely(!(attr & LUDA_IGNORE))) {
4876                 oic->oic_lid = *id;
4877                 oic->oic_fid = *fid;
4878         }
4879
4880         if (!(attr & LUDA_VERIFY) &&
4881             (scrub->os_pos_current <= ino) &&
4882             ((sf->sf_flags & SF_INCONSISTENT) ||
4883              (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
4884              ldiskfs_test_bit(osd_oi_fid2idx(dev, fid), sf->sf_oi_bitmap)))
4885                 osd_consistency_check(oti, dev, oic);
4886
4887         RETURN(rc);
4888 }
4889
4890 /**
4891  * Returns a cookie for current position of the iterator head, so that
4892  * user can use this cookie to load/start the iterator next time.
4893  *
4894  * \param di iterator's in memory structure
4895  *
4896  * \retval cookie for current position, on success
4897  */
4898 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
4899 {
4900         struct osd_it_ea *it = (struct osd_it_ea *)di;
4901
4902         return it->oie_dirent->oied_off;
4903 }
4904
4905 /**
4906  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4907  * to load a directory entry at a time and stored it i inn,
4908  * in iterator's in-memory data structure.
4909  *
4910  * \param di struct osd_it_ea, iterator's in memory structure
4911  *
4912  * \retval +ve on success
4913  * \retval -ve on error
4914  */
4915 static int osd_it_ea_load(const struct lu_env *env,
4916                           const struct dt_it *di, __u64 hash)
4917 {
4918         struct osd_it_ea *it = (struct osd_it_ea *)di;
4919         int rc;
4920
4921         ENTRY;
4922         it->oie_file.f_pos = hash;
4923
4924         rc =  osd_ldiskfs_it_fill(env, di);
4925         if (rc == 0)
4926                 rc = +1;
4927
4928         RETURN(rc);
4929 }
4930
4931 /**
4932  * Index lookup function for interoperability mode (b11826).
4933  *
4934  * \param key,  key i.e. file name to be searched
4935  *
4936  * \retval +ve, on success
4937  * \retval -ve, on error
4938  */
4939 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
4940                                struct dt_rec *rec, const struct dt_key *key,
4941                                struct lustre_capa *capa)
4942 {
4943         struct osd_object *obj = osd_dt_obj(dt);
4944         int rc = 0;
4945
4946         ENTRY;
4947
4948         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
4949         LINVRNT(osd_invariant(obj));
4950
4951         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
4952                 return -EACCES;
4953
4954         rc = osd_ea_lookup_rec(env, obj, rec, key);
4955         if (rc == 0)
4956                 rc = +1;
4957         RETURN(rc);
4958 }
4959
4960 /**
4961  * Index and Iterator operations for interoperability
4962  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
4963  */
4964 static const struct dt_index_operations osd_index_ea_ops = {
4965         .dio_lookup         = osd_index_ea_lookup,
4966         .dio_declare_insert = osd_index_declare_ea_insert,
4967         .dio_insert         = osd_index_ea_insert,
4968         .dio_declare_delete = osd_index_declare_ea_delete,
4969         .dio_delete         = osd_index_ea_delete,
4970         .dio_it     = {
4971                 .init     = osd_it_ea_init,
4972                 .fini     = osd_it_ea_fini,
4973                 .get      = osd_it_ea_get,
4974                 .put      = osd_it_ea_put,
4975                 .next     = osd_it_ea_next,
4976                 .key      = osd_it_ea_key,
4977                 .key_size = osd_it_ea_key_size,
4978                 .rec      = osd_it_ea_rec,
4979                 .store    = osd_it_ea_store,
4980                 .load     = osd_it_ea_load
4981         }
4982 };
4983
4984 static void *osd_key_init(const struct lu_context *ctx,
4985                           struct lu_context_key *key)
4986 {
4987         struct osd_thread_info *info;
4988
4989         OBD_ALLOC_PTR(info);
4990         if (info == NULL)
4991                 return ERR_PTR(-ENOMEM);
4992
4993         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
4994         if (info->oti_it_ea_buf == NULL)
4995                 goto out_free_info;
4996
4997         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
4998
4999         info->oti_hlock = ldiskfs_htree_lock_alloc();
5000         if (info->oti_hlock == NULL)
5001                 goto out_free_ea;
5002
5003         return info;
5004
5005  out_free_ea:
5006         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5007  out_free_info:
5008         OBD_FREE_PTR(info);
5009         return ERR_PTR(-ENOMEM);
5010 }
5011
5012 static void osd_key_fini(const struct lu_context *ctx,
5013                          struct lu_context_key *key, void* data)
5014 {
5015         struct osd_thread_info *info = data;
5016
5017         if (info->oti_hlock != NULL)
5018                 ldiskfs_htree_lock_free(info->oti_hlock);
5019         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5020         OBD_FREE_PTR(info);
5021 }
5022
5023 static void osd_key_exit(const struct lu_context *ctx,
5024                          struct lu_context_key *key, void *data)
5025 {
5026         struct osd_thread_info *info = data;
5027
5028         LASSERT(info->oti_r_locks == 0);
5029         LASSERT(info->oti_w_locks == 0);
5030         LASSERT(info->oti_txns    == 0);
5031 }
5032
5033 /* type constructor/destructor: osd_type_init, osd_type_fini */
5034 LU_TYPE_INIT_FINI(osd, &osd_key);
5035
5036 struct lu_context_key osd_key = {
5037         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
5038         .lct_init = osd_key_init,
5039         .lct_fini = osd_key_fini,
5040         .lct_exit = osd_key_exit
5041 };
5042
5043
5044 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
5045                            const char *name, struct lu_device *next)
5046 {
5047         struct osd_device *osd = osd_dev(d);
5048
5049         strncpy(osd->od_svname, name, MAX_OBD_NAME);
5050         return osd_procfs_init(osd, name);
5051 }
5052
5053 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
5054 {
5055         ENTRY;
5056
5057         osd_scrub_cleanup(env, o);
5058
5059         if (o->od_fsops) {
5060                 fsfilt_put_ops(o->od_fsops);
5061                 o->od_fsops = NULL;
5062         }
5063
5064         /* shutdown quota slave instance associated with the device */
5065         if (o->od_quota_slave != NULL) {
5066                 qsd_fini(env, o->od_quota_slave);
5067                 o->od_quota_slave = NULL;
5068         }
5069
5070         RETURN(0);
5071 }
5072
5073 static int osd_mount(const struct lu_env *env,
5074                      struct osd_device *o, struct lustre_cfg *cfg)
5075 {
5076         const char              *name  = lustre_cfg_string(cfg, 0);
5077         const char              *dev  = lustre_cfg_string(cfg, 1);
5078         const char              *opts;
5079         unsigned long            page, s_flags, lmd_flags = 0;
5080         struct page             *__page;
5081         struct file_system_type *type;
5082         char                    *options = NULL;
5083         char                    *str;
5084         int                       rc = 0;
5085         ENTRY;
5086
5087         if (o->od_mnt != NULL)
5088                 RETURN(0);
5089
5090         if (strlen(dev) >= sizeof(o->od_mntdev))
5091                 RETURN(-E2BIG);
5092         strcpy(o->od_mntdev, dev);
5093
5094         o->od_fsops = fsfilt_get_ops(mt_str(LDD_MT_LDISKFS));
5095         if (o->od_fsops == NULL) {
5096                 CERROR("Can't find fsfilt_ldiskfs\n");
5097                 RETURN(-ENOTSUPP);
5098         }
5099
5100         OBD_PAGE_ALLOC(__page, CFS_ALLOC_STD);
5101         if (__page == NULL)
5102                 GOTO(out, rc = -ENOMEM);
5103
5104         str = lustre_cfg_string(cfg, 2);
5105         s_flags = simple_strtoul(str, NULL, 0);
5106         str = strstr(str, ":");
5107         if (str)
5108                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
5109         opts = lustre_cfg_string(cfg, 3);
5110         page = (unsigned long)cfs_page_address(__page);
5111         options = (char *)page;
5112         *options = '\0';
5113         if (opts == NULL)
5114                 strcat(options, "user_xattr,acl");
5115         else
5116                 strcat(options, opts);
5117
5118         /* Glom up mount options */
5119         if (*options != '\0')
5120                 strcat(options, ",");
5121         strlcat(options, "no_mbcache", CFS_PAGE_SIZE);
5122
5123         type = get_fs_type("ldiskfs");
5124         if (!type) {
5125                 CERROR("%s: cannot find ldiskfs module\n", name);
5126                 GOTO(out, rc = -ENODEV);
5127         }
5128
5129         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
5130         cfs_module_put(type->owner);
5131
5132         if (IS_ERR(o->od_mnt)) {
5133                 rc = PTR_ERR(o->od_mnt);
5134                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
5135                 o->od_mnt = NULL;
5136                 GOTO(out, rc);
5137         }
5138
5139         if (lvfs_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
5140                 CERROR("%s: underlying device %s is marked as read-only. "
5141                        "Setup failed\n", name, dev);
5142                 mntput(o->od_mnt);
5143                 o->od_mnt = NULL;
5144                 GOTO(out, rc = -EROFS);
5145         }
5146
5147         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
5148             LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
5149                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
5150                 mntput(o->od_mnt);
5151                 o->od_mnt = NULL;
5152                 GOTO(out, rc = -EINVAL);
5153         }
5154
5155         ldiskfs_set_inode_state(osd_sb(o)->s_root->d_inode,
5156                                 LDISKFS_STATE_LUSTRE_NO_OI);
5157         if (lmd_flags & LMD_FLG_NOSCRUB)
5158                 o->od_noscrub = 1;
5159
5160 out:
5161         if (__page)
5162                 OBD_PAGE_FREE(__page);
5163         if (rc)
5164                 fsfilt_put_ops(o->od_fsops);
5165
5166         RETURN(rc);
5167 }
5168
5169 static struct lu_device *osd_device_fini(const struct lu_env *env,
5170                                          struct lu_device *d)
5171 {
5172         int rc;
5173         ENTRY;
5174
5175         rc = osd_shutdown(env, osd_dev(d));
5176
5177         osd_obj_map_fini(osd_dev(d));
5178
5179         shrink_dcache_sb(osd_sb(osd_dev(d)));
5180         osd_sync(env, lu2dt_dev(d));
5181
5182         rc = osd_procfs_fini(osd_dev(d));
5183         if (rc) {
5184                 CERROR("proc fini error %d \n", rc);
5185                 RETURN (ERR_PTR(rc));
5186         }
5187
5188         if (osd_dev(d)->od_mnt) {
5189                 mntput(osd_dev(d)->od_mnt);
5190                 osd_dev(d)->od_mnt = NULL;
5191         }
5192
5193         RETURN(NULL);
5194 }
5195
5196 static int osd_device_init0(const struct lu_env *env,
5197                             struct osd_device *o,
5198                             struct lustre_cfg *cfg)
5199 {
5200         struct lu_device        *l = osd2lu_dev(o);
5201         struct osd_thread_info *info;
5202         int                     rc;
5203
5204         /* if the module was re-loaded, env can loose its keys */
5205         rc = lu_env_refill((struct lu_env *) env);
5206         if (rc)
5207                 GOTO(out, rc);
5208         info = osd_oti_get(env);
5209         LASSERT(info);
5210
5211         l->ld_ops = &osd_lu_ops;
5212         o->od_dt_dev.dd_ops = &osd_dt_ops;
5213
5214         spin_lock_init(&o->od_osfs_lock);
5215         mutex_init(&o->od_otable_mutex);
5216         o->od_osfs_age = cfs_time_shift_64(-1000);
5217
5218         o->od_capa_hash = init_capa_hash();
5219         if (o->od_capa_hash == NULL)
5220                 GOTO(out, rc = -ENOMEM);
5221
5222         o->od_read_cache = 1;
5223         o->od_writethrough_cache = 1;
5224         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
5225
5226         rc = osd_mount(env, o, cfg);
5227         if (rc)
5228                 GOTO(out_capa, rc);
5229
5230         CFS_INIT_LIST_HEAD(&o->od_ios_list);
5231         /* setup scrub, including OI files initialization */
5232         rc = osd_scrub_setup(env, o);
5233         if (rc < 0)
5234                 GOTO(out_mnt, rc);
5235
5236         strncpy(o->od_svname, lustre_cfg_string(cfg, 4),
5237                         sizeof(o->od_svname) - 1);
5238
5239         rc = osd_obj_map_init(o);
5240         if (rc != 0)
5241                 GOTO(out_scrub, rc);
5242
5243         rc = lu_site_init(&o->od_site, l);
5244         if (rc)
5245                 GOTO(out_compat, rc);
5246         o->od_site.ls_bottom_dev = l;
5247
5248         rc = lu_site_init_finish(&o->od_site);
5249         if (rc)
5250                 GOTO(out_site, rc);
5251
5252         rc = osd_procfs_init(o, o->od_svname);
5253         if (rc != 0) {
5254                 CERROR("%s: can't initialize procfs: rc = %d\n",
5255                        o->od_svname, rc);
5256                 GOTO(out_site, rc);
5257         }
5258
5259         LASSERT(l->ld_site->ls_linkage.next && l->ld_site->ls_linkage.prev);
5260
5261         /* initialize quota slave instance */
5262         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
5263                                      o->od_proc_entry);
5264         if (IS_ERR(o->od_quota_slave)) {
5265                 rc = PTR_ERR(o->od_quota_slave);
5266                 o->od_quota_slave = NULL;
5267                 GOTO(out_procfs, rc);
5268         }
5269
5270         RETURN(0);
5271 out_procfs:
5272         osd_procfs_fini(o);
5273 out_site:
5274         lu_site_fini(&o->od_site);
5275 out_compat:
5276         osd_obj_map_fini(o);
5277 out_scrub:
5278         osd_scrub_cleanup(env, o);
5279 out_mnt:
5280         osd_oi_fini(info, o);
5281         osd_shutdown(env, o);
5282         mntput(o->od_mnt);
5283         o->od_mnt = NULL;
5284 out_capa:
5285         cleanup_capa_hash(o->od_capa_hash);
5286 out:
5287         RETURN(rc);
5288 }
5289
5290 static struct lu_device *osd_device_alloc(const struct lu_env *env,
5291                                           struct lu_device_type *t,
5292                                           struct lustre_cfg *cfg)
5293 {
5294         struct osd_device *o;
5295         int                rc;
5296
5297         OBD_ALLOC_PTR(o);
5298         if (o == NULL)
5299                 return ERR_PTR(-ENOMEM);
5300
5301         rc = dt_device_init(&o->od_dt_dev, t);
5302         if (rc == 0) {
5303                 /* Because the ctx might be revived in dt_device_init,
5304                  * refill the env here */
5305                 lu_env_refill((struct lu_env *)env);
5306                 rc = osd_device_init0(env, o, cfg);
5307                 if (rc)
5308                         dt_device_fini(&o->od_dt_dev);
5309         }
5310
5311         if (unlikely(rc != 0))
5312                 OBD_FREE_PTR(o);
5313
5314         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
5315 }
5316
5317 static struct lu_device *osd_device_free(const struct lu_env *env,
5318                                          struct lu_device *d)
5319 {
5320         struct osd_device *o = osd_dev(d);
5321         ENTRY;
5322
5323         cleanup_capa_hash(o->od_capa_hash);
5324         /* XXX: make osd top device in order to release reference */
5325         d->ld_site->ls_top_dev = d;
5326         lu_site_purge(env, d->ld_site, -1);
5327         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
5328                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
5329                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
5330         }
5331         lu_site_fini(&o->od_site);
5332         dt_device_fini(&o->od_dt_dev);
5333         OBD_FREE_PTR(o);
5334         RETURN(NULL);
5335 }
5336
5337 static int osd_process_config(const struct lu_env *env,
5338                               struct lu_device *d, struct lustre_cfg *cfg)
5339 {
5340         struct osd_device *o = osd_dev(d);
5341         int err;
5342         ENTRY;
5343
5344         switch(cfg->lcfg_command) {
5345         case LCFG_SETUP:
5346                 err = osd_mount(env, o, cfg);
5347                 break;
5348         case LCFG_CLEANUP:
5349                 lu_dev_del_linkage(d->ld_site, d);
5350                 err = osd_shutdown(env, o);
5351                 break;
5352         default:
5353                 err = -ENOSYS;
5354         }
5355
5356         RETURN(err);
5357 }
5358
5359 static int osd_recovery_complete(const struct lu_env *env,
5360                                  struct lu_device *d)
5361 {
5362         struct osd_device       *osd = osd_dev(d);
5363         int                      rc = 0;
5364         ENTRY;
5365
5366         if (osd->od_quota_slave == NULL)
5367                 RETURN(0);
5368
5369         /* start qsd instance on recovery completion, this notifies the quota
5370          * slave code that we are about to process new requests now */
5371         rc = qsd_start(env, osd->od_quota_slave);
5372         RETURN(rc);
5373 }
5374
5375 /*
5376  * we use exports to track all osd users
5377  */
5378 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
5379                            struct obd_device *obd, struct obd_uuid *cluuid,
5380                            struct obd_connect_data *data, void *localdata)
5381 {
5382         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
5383         struct lustre_handle  conn;
5384         int                   rc;
5385         ENTRY;
5386
5387         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
5388
5389         rc = class_connect(&conn, obd, cluuid);
5390         if (rc)
5391                 RETURN(rc);
5392
5393         *exp = class_conn2export(&conn);
5394
5395         spin_lock(&osd->od_osfs_lock);
5396         osd->od_connects++;
5397         spin_unlock(&osd->od_osfs_lock);
5398
5399         RETURN(0);
5400 }
5401
5402 /*
5403  * once last export (we don't count self-export) disappeared
5404  * osd can be released
5405  */
5406 static int osd_obd_disconnect(struct obd_export *exp)
5407 {
5408         struct obd_device *obd = exp->exp_obd;
5409         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
5410         int                rc, release = 0;
5411         ENTRY;
5412
5413         /* Only disconnect the underlying layers on the final disconnect. */
5414         spin_lock(&osd->od_osfs_lock);
5415         osd->od_connects--;
5416         if (osd->od_connects == 0)
5417                 release = 1;
5418         spin_unlock(&osd->od_osfs_lock);
5419
5420         rc = class_disconnect(exp); /* bz 9811 */
5421
5422         if (rc == 0 && release)
5423                 class_manual_cleanup(obd);
5424         RETURN(rc);
5425 }
5426
5427 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
5428                        struct lu_device *dev)
5429 {
5430         struct osd_device *osd = osd_dev(dev);
5431         int                result = 0;
5432         ENTRY;
5433
5434         if (dev->ld_site && lu_device_is_md(dev->ld_site->ls_top_dev)) {
5435                 /* MDT/MDD still use old infrastructure to create
5436                  * special files */
5437                 result = llo_local_objects_setup(env, lu2md_dev(pdev),
5438                                                  lu2dt_dev(dev));
5439                 if (result)
5440                         RETURN(result);
5441         }
5442
5443         if (osd->od_quota_slave != NULL)
5444                 /* set up quota slave objects */
5445                 result = qsd_prepare(env, osd->od_quota_slave);
5446
5447         RETURN(result);
5448 }
5449
5450 static const struct lu_object_operations osd_lu_obj_ops = {
5451         .loo_object_init      = osd_object_init,
5452         .loo_object_delete    = osd_object_delete,
5453         .loo_object_release   = osd_object_release,
5454         .loo_object_free      = osd_object_free,
5455         .loo_object_print     = osd_object_print,
5456         .loo_object_invariant = osd_object_invariant
5457 };
5458
5459 const struct lu_device_operations osd_lu_ops = {
5460         .ldo_object_alloc      = osd_object_alloc,
5461         .ldo_process_config    = osd_process_config,
5462         .ldo_recovery_complete = osd_recovery_complete,
5463         .ldo_prepare           = osd_prepare,
5464 };
5465
5466 static const struct lu_device_type_operations osd_device_type_ops = {
5467         .ldto_init = osd_type_init,
5468         .ldto_fini = osd_type_fini,
5469
5470         .ldto_start = osd_type_start,
5471         .ldto_stop  = osd_type_stop,
5472
5473         .ldto_device_alloc = osd_device_alloc,
5474         .ldto_device_free  = osd_device_free,
5475
5476         .ldto_device_init    = osd_device_init,
5477         .ldto_device_fini    = osd_device_fini
5478 };
5479
5480 struct lu_device_type osd_device_type = {
5481         .ldt_tags     = LU_DEVICE_DT,
5482         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
5483         .ldt_ops      = &osd_device_type_ops,
5484         .ldt_ctx_tags = LCT_LOCAL,
5485 };
5486
5487 /*
5488  * lprocfs legacy support.
5489  */
5490 static struct obd_ops osd_obd_device_ops = {
5491         .o_owner = THIS_MODULE,
5492         .o_connect      = osd_obd_connect,
5493         .o_disconnect   = osd_obd_disconnect
5494 };
5495
5496 static int __init osd_mod_init(void)
5497 {
5498         struct lprocfs_static_vars lvars;
5499
5500         osd_oi_mod_init();
5501         lprocfs_osd_init_vars(&lvars);
5502         return class_register_type(&osd_obd_device_ops, NULL, lvars.module_vars,
5503                                    LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
5504 }
5505
5506 static void __exit osd_mod_exit(void)
5507 {
5508         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
5509 }
5510
5511 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
5512 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
5513 MODULE_LICENSE("GPL");
5514
5515 cfs_module(osd, "0.1.0", osd_mod_init, osd_mod_exit);