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