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