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