Whamcloud - gitweb
LU-14119 osd: delete stale OI mapping entry
[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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/osd/osd_handler.c
33  *
34  * Top-level entry points into osd module
35  *
36  * Author: Nikita Danilov <nikita@clusterfs.com>
37  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
38  */
39
40 #define DEBUG_SUBSYSTEM S_OSD
41
42 #include <linux/kallsyms.h>
43 #include <linux/module.h>
44 #include <linux/user_namespace.h>
45 #ifdef HAVE_UIDGID_HEADER
46 # include <linux/uidgid.h>
47 #endif
48
49 /* prerequisite for linux/xattr.h */
50 #include <linux/types.h>
51 /* prerequisite for linux/xattr.h */
52 #include <linux/fs.h>
53 /* XATTR_{REPLACE,CREATE} */
54 #include <linux/xattr.h>
55
56 #include <ldiskfs/ldiskfs.h>
57 #include <ldiskfs/xattr.h>
58 #include <ldiskfs/ldiskfs_extents.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 <uapi/linux/lustre/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 /* Maximum EA size is limited by LNET_MTU for remote objects */
81 #define OSD_MAX_EA_SIZE 1048364
82
83 int ldiskfs_pdo = 1;
84 module_param(ldiskfs_pdo, int, 0644);
85 MODULE_PARM_DESC(ldiskfs_pdo, "ldiskfs with parallel directory operations");
86
87 int ldiskfs_track_declares_assert;
88 module_param(ldiskfs_track_declares_assert, int, 0644);
89 MODULE_PARM_DESC(ldiskfs_track_declares_assert, "LBUG during tracking of declares");
90
91 /* Slab to allocate dynlocks */
92 struct kmem_cache *dynlock_cachep;
93
94 /* Slab to allocate osd_it_ea */
95 struct kmem_cache *osd_itea_cachep;
96
97 static struct lu_kmem_descr ldiskfs_caches[] = {
98         {
99                 .ckd_cache = &dynlock_cachep,
100                 .ckd_name  = "dynlock_cache",
101                 .ckd_size  = sizeof(struct dynlock_handle)
102         },
103         {
104                 .ckd_cache = &osd_itea_cachep,
105                 .ckd_name  = "osd_itea_cache",
106                 .ckd_size  = sizeof(struct osd_it_ea)
107         },
108         {
109                 .ckd_cache = NULL
110         }
111 };
112
113 static const char dot[] = ".";
114 static const char dotdot[] = "..";
115
116 static const struct lu_object_operations      osd_lu_obj_ops;
117 static const struct dt_object_operations      osd_obj_ops;
118 static const struct dt_object_operations      osd_obj_otable_it_ops;
119 static const struct dt_index_operations       osd_index_iam_ops;
120 static const struct dt_index_operations       osd_index_ea_ops;
121
122 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
123                           const struct lu_fid *fid);
124 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
125                                                 struct osd_device *osd);
126
127 int osd_trans_declare_op2rb[] = {
128         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
129         [OSD_OT_PUNCH]          = OSD_OT_MAX,
130         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
131         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
132         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
133         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
134         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
135         [OSD_OT_WRITE]          = OSD_OT_WRITE,
136         [OSD_OT_INSERT]         = OSD_OT_DELETE,
137         [OSD_OT_DELETE]         = OSD_OT_INSERT,
138         [OSD_OT_QUOTA]          = OSD_OT_MAX,
139 };
140
141 static int osd_has_index(const struct osd_object *obj)
142 {
143         return obj->oo_dt.do_index_ops != NULL;
144 }
145
146 static int osd_object_invariant(const struct lu_object *l)
147 {
148         return osd_invariant(osd_obj(l));
149 }
150
151 /*
152  * Concurrency: doesn't matter
153  */
154 static int osd_is_write_locked(const struct lu_env *env, struct osd_object *o)
155 {
156         struct osd_thread_info *oti = osd_oti_get(env);
157
158         return oti->oti_w_locks > 0 && o->oo_owner == env;
159 }
160
161 /*
162  * Concurrency: doesn't access mutable data
163  */
164 static int osd_root_get(const struct lu_env *env,
165                         struct dt_device *dev, struct lu_fid *f)
166 {
167         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
168         return 0;
169 }
170
171 /*
172  * the following set of functions are used to maintain per-thread
173  * cache of FID->ino mapping. this mechanism is needed to resolve
174  * FID to inode at dt_insert() which in turn stores ino in the
175  * directory entries to keep ldiskfs compatible with ext[34].
176  * due to locking-originated restrictions we can't lookup ino
177  * using LU cache (deadlock is possible). lookup using OI is quite
178  * expensive. so instead we maintain this cache and methods like
179  * dt_create() fill it. so in the majority of cases dt_insert() is
180  * able to find needed mapping in lockless manner.
181  */
182 static struct osd_idmap_cache *
183 osd_idc_find(const struct lu_env *env, struct osd_device *osd,
184              const struct lu_fid *fid)
185 {
186         struct osd_thread_info *oti = osd_oti_get(env);
187         struct osd_idmap_cache *idc = oti->oti_ins_cache;
188         int i;
189
190         for (i = 0; i < oti->oti_ins_cache_used; i++) {
191                 if (!lu_fid_eq(&idc[i].oic_fid, fid))
192                         continue;
193                 if (idc[i].oic_dev != osd)
194                         continue;
195
196                 return idc + i;
197         }
198
199         return NULL;
200 }
201
202 static struct osd_idmap_cache *
203 osd_idc_add(const struct lu_env *env, struct osd_device *osd,
204             const struct lu_fid *fid)
205 {
206         struct osd_thread_info *oti   = osd_oti_get(env);
207         struct osd_idmap_cache *idc;
208         int i;
209
210         if (unlikely(oti->oti_ins_cache_used >= oti->oti_ins_cache_size)) {
211                 i = oti->oti_ins_cache_size * 2;
212                 if (i == 0)
213                         i = OSD_INS_CACHE_SIZE;
214                 OBD_ALLOC(idc, sizeof(*idc) * i);
215                 if (idc == NULL)
216                         return ERR_PTR(-ENOMEM);
217                 if (oti->oti_ins_cache != NULL) {
218                         memcpy(idc, oti->oti_ins_cache,
219                                oti->oti_ins_cache_used * sizeof(*idc));
220                         OBD_FREE(oti->oti_ins_cache,
221                                  oti->oti_ins_cache_used * sizeof(*idc));
222                 }
223                 oti->oti_ins_cache = idc;
224                 oti->oti_ins_cache_size = i;
225         }
226
227         idc = oti->oti_ins_cache + oti->oti_ins_cache_used++;
228         idc->oic_fid = *fid;
229         idc->oic_dev = osd;
230         idc->oic_lid.oii_ino = 0;
231         idc->oic_lid.oii_gen = 0;
232         idc->oic_remote = 0;
233
234         return idc;
235 }
236
237 /*
238  * lookup mapping for the given fid in the cache, initialize a
239  * new one if not found. the initialization checks whether the
240  * object is local or remote. for local objects, OI is used to
241  * learn ino/generation. the function is used when the caller
242  * has no information about the object, e.g. at dt_insert().
243  */
244 static struct osd_idmap_cache *
245 osd_idc_find_or_init(const struct lu_env *env, struct osd_device *osd,
246                      const struct lu_fid *fid)
247 {
248         struct osd_idmap_cache *idc;
249         int rc;
250
251         idc = osd_idc_find(env, osd, fid);
252         LASSERT(!IS_ERR(idc));
253         if (idc != NULL)
254                 return idc;
255
256         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
257                osd->od_svname, PFID(fid));
258
259         /* new mapping is needed */
260         idc = osd_idc_add(env, osd, fid);
261         if (IS_ERR(idc)) {
262                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
263                        osd->od_svname, PFID(fid), PTR_ERR(idc));
264                 return idc;
265         }
266
267         /* initialize it */
268         rc = osd_remote_fid(env, osd, fid);
269         if (unlikely(rc < 0))
270                 return ERR_PTR(rc);
271
272         if (rc == 0) {
273                 /* the object is local, lookup in OI */
274                 /* XXX: probably cheaper to lookup in LU first? */
275                 rc = osd_oi_lookup(osd_oti_get(env), osd, fid,
276                                    &idc->oic_lid, 0);
277                 if (unlikely(rc < 0)) {
278                         CERROR("can't lookup: rc = %d\n", rc);
279                         return ERR_PTR(rc);
280                 }
281         } else {
282                 /* the object is remote */
283                 idc->oic_remote = 1;
284         }
285
286         return idc;
287 }
288
289 static void osd_idc_dump_lma(const struct lu_env *env,
290                                 struct osd_device *osd,
291                                 unsigned long ino,
292                                 bool check_in_oi)
293 {
294         struct osd_thread_info *info = osd_oti_get(env);
295         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
296         const struct lu_fid *fid;
297         struct osd_inode_id lid;
298         struct inode *inode;
299         int rc;
300
301         inode = ldiskfs_iget(osd_sb(osd), ino);
302         if (IS_ERR(inode)) {
303                 CERROR("%s: can't get inode %lu: rc = %d\n",
304                        osd->od_svname, ino, (int)PTR_ERR(inode));
305                 return;
306         }
307         if (is_bad_inode(inode)) {
308                 CERROR("%s: bad inode %lu\n", osd->od_svname, ino);
309                 goto put;
310         }
311         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
312         if (rc) {
313                 CERROR("%s: can't get LMA for %lu: rc = %d\n",
314                        osd->od_svname, ino, rc);
315                 goto put;
316         }
317         fid = &loa->loa_lma.lma_self_fid;
318         LCONSOLE(D_INFO, "%s: "DFID" in inode %lu/%u\n", osd->od_svname,
319                       PFID(fid), ino, (unsigned)inode->i_generation);
320         if (!check_in_oi)
321                 goto put;
322         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
323         if (rc) {
324                 CERROR("%s: can't lookup "DFID": rc = %d\n",
325                        osd->od_svname, PFID(fid), rc);
326                 goto put;
327         }
328         LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n", osd->od_svname,
329                       PFID(fid), lid.oii_ino, lid.oii_gen);
330 put:
331         iput(inode);
332 }
333
334 static void osd_idc_dump_debug(const struct lu_env *env,
335                                 struct osd_device *osd,
336                                 const struct lu_fid *fid,
337                                 unsigned long ino1,
338                                 unsigned long ino2)
339 {
340         struct osd_inode_id lid;
341
342         int rc;
343
344         rc = osd_oi_lookup(osd_oti_get(env), osd, fid, &lid, 0);
345         if (!rc) {
346                 LCONSOLE(D_INFO, "%s: "DFID" maps to %u/%u\n",
347                         osd->od_svname, PFID(fid), lid.oii_ino, lid.oii_gen);
348                 osd_idc_dump_lma(env, osd, lid.oii_ino, false);
349         } else {
350                 CERROR("%s: can't lookup "DFID": rc = %d\n",
351                        osd->od_svname, PFID(fid), rc);
352         }
353         if (ino1)
354                 osd_idc_dump_lma(env, osd, ino1, true);
355         if (ino2)
356                 osd_idc_dump_lma(env, osd, ino2, true);
357 }
358
359 /*
360  * lookup mapping for given FID and fill it from the given object.
361  * the object is lolcal by definition.
362  */
363 static int osd_idc_find_and_init(const struct lu_env *env,
364                                  struct osd_device *osd,
365                                  struct osd_object *obj)
366 {
367         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
368         struct osd_idmap_cache *idc;
369
370         idc = osd_idc_find(env, osd, fid);
371         LASSERT(!IS_ERR(idc));
372         if (idc != NULL) {
373                 if (obj->oo_inode == NULL)
374                         return 0;
375                 if (idc->oic_lid.oii_ino != obj->oo_inode->i_ino) {
376                         if (idc->oic_lid.oii_ino) {
377                                 osd_idc_dump_debug(env, osd, fid,
378                                                    idc->oic_lid.oii_ino,
379                                                    obj->oo_inode->i_ino);
380                                 return -EINVAL;
381                         }
382                         idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
383                         idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
384                 }
385                 return 0;
386         }
387
388         CDEBUG(D_INODE, "%s: FID "DFID" not in the id map cache\n",
389                osd->od_svname, PFID(fid));
390
391         /* new mapping is needed */
392         idc = osd_idc_add(env, osd, fid);
393         if (IS_ERR(idc)) {
394                 CERROR("%s: FID "DFID" add id map cache failed: %ld\n",
395                        osd->od_svname, PFID(fid), PTR_ERR(idc));
396                 return PTR_ERR(idc);
397         }
398
399         if (obj->oo_inode != NULL) {
400                 idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
401                 idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
402         }
403         return 0;
404 }
405
406 /*
407  * OSD object methods.
408  */
409
410 /*
411  * Concurrency: no concurrent access is possible that early in object
412  * life-cycle.
413  */
414 static struct lu_object *osd_object_alloc(const struct lu_env *env,
415                                           const struct lu_object_header *hdr,
416                                           struct lu_device *d)
417 {
418         struct osd_object *mo;
419
420         OBD_ALLOC_PTR(mo);
421         if (mo != NULL) {
422                 struct lu_object *l;
423                 struct lu_object_header *h;
424                 struct osd_device *o = osd_dev(d);
425
426                 l = &mo->oo_dt.do_lu;
427                 if (unlikely(o->od_in_init)) {
428                         OBD_ALLOC_PTR(h);
429                         if (!h) {
430                                 OBD_FREE_PTR(mo);
431                                 return NULL;
432                         }
433
434                         lu_object_header_init(h);
435                         lu_object_init(l, h, d);
436                         lu_object_add_top(h, l);
437                         mo->oo_header = h;
438                 } else {
439                         dt_object_init(&mo->oo_dt, NULL, d);
440                         mo->oo_header = NULL;
441                 }
442
443                 mo->oo_dt.do_ops = &osd_obj_ops;
444                 l->lo_ops = &osd_lu_obj_ops;
445                 init_rwsem(&mo->oo_sem);
446                 init_rwsem(&mo->oo_ext_idx_sem);
447                 spin_lock_init(&mo->oo_guard);
448                 INIT_LIST_HEAD(&mo->oo_xattr_list);
449                 return l;
450         }
451         return NULL;
452 }
453
454 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
455                 struct dentry *dentry, struct lustre_ost_attrs *loa)
456 {
457         int rc;
458
459         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
460                              (void *)loa, sizeof(*loa));
461         if (rc > 0) {
462                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
463
464                 if (rc < sizeof(*lma))
465                         return -EINVAL;
466
467                 rc = 0;
468                 lustre_loa_swab(loa, true);
469                 /* Check LMA compatibility */
470                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
471                         CWARN("%s: unsupported incompat LMA feature(s) %#x "
472                               "for fid = "DFID", ino = %lu\n",
473                               osd_ino2name(inode),
474                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
475                               PFID(&lma->lma_self_fid), inode->i_ino);
476                         rc = -EOPNOTSUPP;
477                 }
478         } else if (rc == 0) {
479                 rc = -ENODATA;
480         }
481
482         return rc;
483 }
484
485 /*
486  * retrieve object from backend ext fs.
487  **/
488 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
489                        struct osd_inode_id *id)
490 {
491         int rc;
492         struct inode *inode = NULL;
493
494         /*
495          * if we look for an inode withing a running
496          * transaction, then we risk to deadlock
497          * osd_dirent_check_repair() breaks this
498          */
499          /* LASSERT(current->journal_info == NULL); */
500
501         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
502         if (IS_ERR(inode)) {
503                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
504                        id->oii_ino, PTR_ERR(inode));
505         } else if (id->oii_gen != OSD_OII_NOGEN &&
506                    inode->i_generation != id->oii_gen) {
507                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
508                        "i_generation = %u\n",
509                        id->oii_ino, id->oii_gen, inode->i_generation);
510                 iput(inode);
511                 inode = ERR_PTR(-ESTALE);
512         } else if (inode->i_nlink == 0) {
513                 /*
514                  * due to parallel readdir and unlink,
515                  * we can have dead inode here.
516                  */
517                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
518                 iput(inode);
519                 inode = ERR_PTR(-ESTALE);
520         } else if (is_bad_inode(inode)) {
521                 CWARN("%s: bad inode: ino = %u\n",
522                       osd_dev2name(dev), id->oii_ino);
523                 iput(inode);
524                 inode = ERR_PTR(-ENOENT);
525         } else if ((rc = osd_attach_jinode(inode))) {
526                 iput(inode);
527                 inode = ERR_PTR(rc);
528         } else {
529                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
530                 if (id->oii_gen == OSD_OII_NOGEN)
531                         osd_id_gen(id, inode->i_ino, inode->i_generation);
532
533                 /*
534                  * Do not update file c/mtime in ldiskfs.
535                  * NB: we don't have any lock to protect this because we don't
536                  * have reference on osd_object now, but contention with
537                  * another lookup + attr_set can't happen in the tiny window
538                  * between if (...) and set S_NOCMTIME.
539                  */
540                 if (!(inode->i_flags & S_NOCMTIME))
541                         inode->i_flags |= S_NOCMTIME;
542         }
543         return inode;
544 }
545
546 int osd_ldiskfs_add_entry(struct osd_thread_info *info, struct osd_device *osd,
547                           handle_t *handle, struct dentry *child,
548                           struct inode *inode, struct htree_lock *hlock)
549 {
550         int rc, rc2;
551
552         rc = __ldiskfs_add_entry(handle, child, inode, hlock);
553         if (rc == -ENOBUFS || rc == -ENOSPC) {
554                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
555                 struct inode *parent = child->d_parent->d_inode;
556                 struct lu_fid *fid = NULL;
557
558                 rc2 = osd_get_lma(info, parent, child->d_parent, loa);
559                 if (!rc2) {
560                         fid = &loa->loa_lma.lma_self_fid;
561                 } else if (rc2 == -ENODATA) {
562                         if (unlikely(parent == inode->i_sb->s_root->d_inode)) {
563                                 fid = &info->oti_fid3;
564                                 lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
565                         } else if (!osd->od_is_ost && osd->od_index == 0) {
566                                 fid = &info->oti_fid3;
567                                 lu_igif_build(fid, parent->i_ino,
568                                               parent->i_generation);
569                         }
570                 }
571
572                 if (fid != NULL)
573                         CWARN("%s: directory (inode: %lu, FID: "DFID") %s "
574                               "maximum entry limit\n",
575                               osd_name(osd), parent->i_ino, PFID(fid),
576                               rc == -ENOSPC ? "has reached" : "is approaching");
577                 else
578                         CWARN("%s: directory (inode: %lu, FID: unknown) %s "
579                               "maximum entry limit\n",
580                               osd_name(osd), parent->i_ino,
581                               rc == -ENOSPC ? "has reached" : "is approaching");
582
583                 /* ignore such error now */
584                 if (rc == -ENOBUFS)
585                         rc = 0;
586         }
587
588         return rc;
589 }
590
591
592 struct inode *
593 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
594              struct osd_inode_id *id, struct lu_fid *fid)
595 {
596         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
597         struct inode *inode;
598         int rc;
599
600         inode = osd_iget(info, dev, id);
601         if (IS_ERR(inode))
602                 return inode;
603
604         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
605         if (!rc) {
606                 *fid = loa->loa_lma.lma_self_fid;
607         } else if (rc == -ENODATA) {
608                 if (unlikely(inode == osd_sb(dev)->s_root->d_inode))
609                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
610                 else
611                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
612         } else {
613                 iput(inode);
614                 inode = ERR_PTR(rc);
615         }
616         return inode;
617 }
618
619 static struct inode *osd_iget_check(struct osd_thread_info *info,
620                                     struct osd_device *dev,
621                                     const struct lu_fid *fid,
622                                     struct osd_inode_id *id,
623                                     bool trusted)
624 {
625         struct inode *inode;
626         int rc = 0;
627
628         ENTRY;
629
630         /*
631          * The cached OI mapping is trustable. If we cannot locate the inode
632          * via the cached OI mapping, then return the failure to the caller
633          * directly without further OI checking.
634          */
635
636 again:
637         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
638         if (IS_ERR(inode)) {
639                 rc = PTR_ERR(inode);
640                 if (!trusted && (rc == -ENOENT || rc == -ESTALE))
641                         goto check_oi;
642
643                 CDEBUG(D_INODE, "no inode for FID: "DFID", ino = %u, rc = %d\n",
644                        PFID(fid), id->oii_ino, rc);
645                 GOTO(put, rc);
646         }
647
648         if (is_bad_inode(inode)) {
649                 rc = -ENOENT;
650                 if (!trusted)
651                         goto check_oi;
652
653                 CDEBUG(D_INODE, "bad inode for FID: "DFID", ino = %u\n",
654                        PFID(fid), id->oii_ino);
655                 GOTO(put, rc);
656         }
657
658         if (id->oii_gen != OSD_OII_NOGEN &&
659             inode->i_generation != id->oii_gen) {
660                 rc = -ESTALE;
661                 if (!trusted)
662                         goto check_oi;
663
664                 CDEBUG(D_INODE, "unmatched inode for FID: "DFID", ino = %u, "
665                        "oii_gen = %u, i_generation = %u\n", PFID(fid),
666                        id->oii_ino, id->oii_gen, inode->i_generation);
667                 GOTO(put, rc);
668         }
669
670         if (inode->i_nlink == 0) {
671                 rc = -ENOENT;
672                 if (!trusted)
673                         goto check_oi;
674
675                 CDEBUG(D_INODE, "stale inode for FID: "DFID", ino = %u\n",
676                        PFID(fid), id->oii_ino);
677                 GOTO(put, rc);
678         }
679
680         ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
681
682 check_oi:
683         if (rc != 0) {
684                 __u32 saved_ino = id->oii_ino;
685                 __u32 saved_gen = id->oii_gen;
686
687                 LASSERT(!trusted);
688                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
689
690                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
691                 /*
692                  * XXX: There are four possible cases:
693                  *      1. rc = 0.
694                  *         Backup/restore caused the OI invalid.
695                  *      2. rc = 0.
696                  *         Someone unlinked the object but NOT removed
697                  *         the OI mapping, such as mount target device
698                  *         as ldiskfs, and modify something directly.
699                  *      3. rc = -ENOENT.
700                  *         Someone just removed the object between the
701                  *         former oi_lookup and the iget. It is normal.
702                  *      4. Other failure cases.
703                  *
704                  *      Generally, when the device is mounted, it will
705                  *      auto check whether the system is restored from
706                  *      file-level backup or not. We trust such detect
707                  *      to distinguish the 1st case from the 2nd case:
708                  *      if the OI files are consistent but may contain
709                  *      stale OI mappings because of case 2, if iget()
710                  *      returns -ENOENT or -ESTALE, then it should be
711                  *      the case 2.
712                  */
713                 if (rc != 0)
714                         /*
715                          * If the OI mapping was in OI file before the
716                          * osd_iget_check(), but now, it is disappear,
717                          * then it must be removed by race. That is a
718                          * normal race case.
719                          */
720                         GOTO(put, rc);
721
722                 /*
723                  * It is the OI scrub updated the OI mapping by race.
724                  * The new OI mapping must be valid.
725                  */
726                 if (saved_ino != id->oii_ino ||
727                     (saved_gen != id->oii_gen && saved_gen != OSD_OII_NOGEN)) {
728                         if (!IS_ERR(inode))
729                                 iput(inode);
730
731                         trusted = true;
732                         goto again;
733                 }
734
735                 if (IS_ERR(inode)) {
736                         if (dev->od_scrub.os_scrub.os_file.sf_flags &
737                             SF_INCONSISTENT)
738                                 /*
739                                  * It still can be the case 2, but we cannot
740                                  * distinguish it from the case 1. So return
741                                  * -EREMCHG to block current operation until
742                                  *  OI scrub rebuilt the OI mappings.
743                                  */
744                                 rc = -EREMCHG;
745                         else
746                                 rc = -ENOENT;
747
748                         GOTO(put, rc);
749                 }
750
751                 if (inode->i_generation == id->oii_gen)
752                         rc = -ENOENT;
753                 else
754                         rc = -EREMCHG;
755         } else {
756                 if (id->oii_gen == OSD_OII_NOGEN)
757                         osd_id_gen(id, inode->i_ino, inode->i_generation);
758
759                 /*
760                  * Do not update file c/mtime in ldiskfs.
761                  * NB: we don't have any lock to protect this because we don't
762                  * have reference on osd_object now, but contention with
763                  * another lookup + attr_set can't happen in the tiny window
764                  * between if (...) and set S_NOCMTIME.
765                  */
766                 if (!(inode->i_flags & S_NOCMTIME))
767                         inode->i_flags |= S_NOCMTIME;
768         }
769
770         GOTO(put, rc);
771
772 put:
773         if (rc != 0) {
774                 if (!IS_ERR(inode))
775                         iput(inode);
776
777                 inode = ERR_PTR(rc);
778         }
779
780         return inode;
781 }
782
783 /**
784  * \retval +v: new filter_fid does not contain self-fid
785  * \retval 0:  filter_fid_18_23, contains self-fid
786  * \retval -v: other failure cases
787  */
788 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
789                  struct dentry *dentry, struct lu_fid *fid)
790 {
791         struct filter_fid *ff = &info->oti_ff;
792         struct ost_id *ostid = &info->oti_ostid;
793         int rc;
794
795         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
796         if (rc == sizeof(struct filter_fid_18_23)) {
797                 struct filter_fid_18_23 *ff_old = (void *)ff;
798
799                 ostid_set_seq(ostid, le64_to_cpu(ff_old->ff_seq));
800                 rc = ostid_set_id(ostid, le64_to_cpu(ff_old->ff_objid));
801                 /*
802                  * XXX: use 0 as the index for compatibility, the caller will
803                  * handle index related issues when necessary.
804                  */
805                 if (!rc)
806                         ostid_to_fid(fid, ostid, 0);
807         } else if (rc >= (int)sizeof(struct filter_fid_24_29)) {
808                 rc = 1;
809         } else if (rc >= 0) {
810                 rc = -EINVAL;
811         }
812
813         return rc;
814 }
815
816 static int osd_lma_self_repair(struct osd_thread_info *info,
817                                struct osd_device *osd, struct inode *inode,
818                                const struct lu_fid *fid, __u32 compat)
819 {
820         handle_t *jh;
821         int rc;
822
823         LASSERT(current->journal_info == NULL);
824
825         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
826                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
827         if (IS_ERR(jh)) {
828                 rc = PTR_ERR(jh);
829                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
830                       osd_name(osd), rc);
831                 return rc;
832         }
833
834         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
835         if (rc != 0)
836                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
837                       osd_name(osd), rc);
838         ldiskfs_journal_stop(jh);
839         return rc;
840 }
841
842 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
843 {
844         struct osd_thread_info *info = osd_oti_get(env);
845         struct osd_device *osd = osd_obj2dev(obj);
846         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
847         struct lustre_mdt_attrs *lma = &loa->loa_lma;
848         struct inode *inode = obj->oo_inode;
849         struct dentry *dentry = &info->oti_obj_dentry;
850         struct lu_fid *fid = NULL;
851         const struct lu_fid *rfid = lu_object_fid(&obj->oo_dt.do_lu);
852         int rc;
853
854         ENTRY;
855
856         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
857                              (void *)loa, sizeof(*loa));
858         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
859                 fid = &lma->lma_self_fid;
860                 rc = osd_get_idif(info, inode, dentry, fid);
861                 if (rc > 0 || (rc == -ENODATA && osd->od_index_in_idif)) {
862                         /*
863                          * For the given OST-object, if it has neither LMA nor
864                          * FID in XATTR_NAME_FID, then the given FID (which is
865                          * contained in the @obj, from client RPC for locating
866                          * the OST-object) is trusted. We use it to generate
867                          * the LMA.
868                          */
869                         osd_lma_self_repair(info, osd, inode, rfid,
870                                             LMAC_FID_ON_OST);
871                         RETURN(0);
872                 }
873         }
874
875         if (rc < 0)
876                 RETURN(rc);
877
878         if (rc > 0) {
879                 rc = 0;
880                 lustre_lma_swab(lma);
881                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
882                              (CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT) &&
883                               S_ISREG(inode->i_mode)))) {
884                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
885                               "fid = "DFID", ino = %lu\n", osd_name(osd),
886                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
887                               PFID(rfid), inode->i_ino);
888                         rc = -EOPNOTSUPP;
889                 } else {
890                         fid = &lma->lma_self_fid;
891                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
892                             osd->od_is_ost)
893                                 obj->oo_pfid_in_lma = 1;
894                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
895                             !osd->od_is_ost)
896                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
897                 }
898         }
899
900         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
901                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
902                         struct ost_id   *oi   = &info->oti_ostid;
903                         struct lu_fid   *fid1 = &info->oti_fid3;
904                         __u32            idx  = fid_idif_ost_idx(rfid);
905
906                         /*
907                          * For old IDIF, the OST index is not part of the IDIF,
908                          * Means that different OSTs may have the same IDIFs.
909                          * Under such case, we need to make some compatible
910                          * check to make sure to trigger OI scrub properly.
911                          */
912                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
913                                 /* Given @rfid is new, LMA is old. */
914                                 fid_to_ostid(fid, oi);
915                                 ostid_to_fid(fid1, oi, idx);
916                                 if (lu_fid_eq(fid1, rfid)) {
917                                         if (osd->od_index_in_idif)
918                                                 osd_lma_self_repair(info, osd,
919                                                         inode, rfid,
920                                                         LMAC_FID_ON_OST);
921                                         RETURN(0);
922                                 }
923                         }
924                 }
925
926                 rc = -EREMCHG;
927         }
928
929         RETURN(rc);
930 }
931
932 struct osd_check_lmv_buf {
933 #ifdef HAVE_DIR_CONTEXT
934         /* please keep it as first member */
935         struct dir_context ctx;
936 #endif
937         struct osd_thread_info *oclb_info;
938         struct osd_device *oclb_dev;
939         int oclb_items;
940         bool oclb_found;
941 };
942
943 /**
944  * It is called internally by ->readdir() to filter out the
945  * local slave object's FID of the striped directory.
946  *
947  * \retval      1 found the local slave's FID
948  * \retval      0 continue to check next item
949  * \retval      -ve for failure
950  */
951 #ifdef HAVE_FILLDIR_USE_CTX
952 static int osd_stripe_dir_filldir(struct dir_context *buf,
953 #else
954 static int osd_stripe_dir_filldir(void *buf,
955 #endif
956                                   const char *name, int namelen,
957                                   loff_t offset, __u64 ino, unsigned int d_type)
958 {
959         struct osd_check_lmv_buf *oclb = (struct osd_check_lmv_buf *)buf;
960         struct osd_thread_info *oti = oclb->oclb_info;
961         struct lu_fid *fid = &oti->oti_fid3;
962         struct osd_inode_id *id = &oti->oti_id3;
963         struct osd_device *dev = oclb->oclb_dev;
964         struct inode *inode;
965
966         oclb->oclb_items++;
967
968         if (name[0] == '.')
969                 return 0;
970
971         fid_zero(fid);
972         sscanf(name + 1, SFID, RFID(fid));
973         if (!fid_is_sane(fid))
974                 return 0;
975
976         if (osd_remote_fid(oti->oti_env, dev, fid))
977                 return 0;
978
979         osd_id_gen(id, ino, OSD_OII_NOGEN);
980         inode = osd_iget(oti, dev, id);
981         if (IS_ERR(inode))
982                 return PTR_ERR(inode);
983
984         iput(inode);
985         osd_add_oi_cache(oti, dev, id, fid);
986         osd_oii_insert(dev, fid, id, true);
987         oclb->oclb_found = true;
988
989         return 1;
990 }
991
992 /*
993  * When lookup item under striped directory, we need to locate the master
994  * MDT-object of the striped directory firstly, then the client will send
995  * lookup (getattr_by_name) RPC to the MDT with some slave MDT-object's FID
996  * and the item's name. If the system is restored from MDT file level backup,
997  * then before the OI scrub completely built the OI files, the OI mappings of
998  * the master MDT-object and slave MDT-object may be invalid. Usually, it is
999  * not a problem for the master MDT-object. Because when locate the master
1000  * MDT-object, we will do name based lookup (for the striped directory itself)
1001  * firstly, during such process we can setup the correct OI mapping for the
1002  * master MDT-object. But it will be trouble for the slave MDT-object. Because
1003  * the client will not trigger name based lookup on the MDT to locate the slave
1004  * MDT-object before locating item under the striped directory, then when
1005  * osd_fid_lookup(), it will find that the OI mapping for the slave MDT-object
1006  * is invalid and does not know what the right OI mapping is, then the MDT has
1007  * to return -EINPROGRESS to the client to notify that the OI scrub is rebuiding
1008  * the OI file, related OI mapping is unknown yet, please try again later. And
1009  * then client will re-try the RPC again and again until related OI mapping has
1010  * been updated. That is quite inefficient.
1011  *
1012  * To resolve above trouble, we will handle it as the following two cases:
1013  *
1014  * 1) The slave MDT-object and the master MDT-object are on different MDTs.
1015  *    It is relative easy. Be as one of remote MDT-objects, the slave MDT-object
1016  *    is linked under /REMOTE_PARENT_DIR with the name of its FID string.
1017  *    We can locate the slave MDT-object via lookup the /REMOTE_PARENT_DIR
1018  *    directly. Please check osd_fid_lookup().
1019  *
1020  * 2) The slave MDT-object and the master MDT-object reside on the same MDT.
1021  *    Under such case, during lookup the master MDT-object, we will lookup the
1022  *    slave MDT-object via readdir against the master MDT-object, because the
1023  *    slave MDT-objects information are stored as sub-directories with the name
1024  *    "${FID}:${index}". Then when find the local slave MDT-object, its OI
1025  *    mapping will be recorded. Then subsequent osd_fid_lookup() will know
1026  *    the correct OI mapping for the slave MDT-object.
1027  */
1028 static int osd_check_lmv(struct osd_thread_info *oti, struct osd_device *dev,
1029                          struct inode *inode)
1030 {
1031         struct lu_buf *buf = &oti->oti_big_buf;
1032         struct dentry *dentry = &oti->oti_obj_dentry;
1033         struct file *filp = &oti->oti_file;
1034         const struct file_operations *fops;
1035         struct lmv_mds_md_v1 *lmv1;
1036         struct osd_check_lmv_buf oclb = {
1037 #ifdef HAVE_DIR_CONTEXT
1038                 .ctx.actor = osd_stripe_dir_filldir,
1039 #endif
1040                 .oclb_info = oti,
1041                 .oclb_dev = dev,
1042                 .oclb_found = false,
1043         };
1044         int rc = 0;
1045
1046         ENTRY;
1047
1048 again:
1049         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMV, buf->lb_buf,
1050                              buf->lb_len);
1051         if (rc == -ERANGE) {
1052                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMV, NULL, 0);
1053                 if (rc > 0) {
1054                         lu_buf_realloc(buf, rc);
1055                         if (buf->lb_buf == NULL)
1056                                 GOTO(out, rc = -ENOMEM);
1057
1058                         goto again;
1059                 }
1060         }
1061
1062         if (unlikely(rc == 0 || rc == -ENODATA))
1063                 GOTO(out, rc = 0);
1064
1065         if (rc < 0)
1066                 GOTO(out, rc);
1067
1068         if (unlikely(buf->lb_buf == NULL)) {
1069                 lu_buf_realloc(buf, rc);
1070                 if (buf->lb_buf == NULL)
1071                         GOTO(out, rc = -ENOMEM);
1072
1073                 goto again;
1074         }
1075
1076         lmv1 = buf->lb_buf;
1077         if (le32_to_cpu(lmv1->lmv_magic) != LMV_MAGIC_V1)
1078                 GOTO(out, rc = 0);
1079
1080         fops = inode->i_fop;
1081         dentry->d_inode = inode;
1082         dentry->d_sb = inode->i_sb;
1083         filp->f_pos = 0;
1084         filp->f_path.dentry = dentry;
1085         filp->f_mode = FMODE_64BITHASH;
1086         filp->f_mapping = inode->i_mapping;
1087         filp->f_op = fops;
1088         filp->private_data = NULL;
1089         set_file_inode(filp, inode);
1090
1091         do {
1092                 oclb.oclb_items = 0;
1093 #ifdef HAVE_DIR_CONTEXT
1094                 oclb.ctx.pos = filp->f_pos;
1095 #ifdef HAVE_ITERATE_SHARED
1096                 rc = fops->iterate_shared(filp, &oclb.ctx);
1097 #else
1098                 rc = fops->iterate(filp, &oclb.ctx);
1099 #endif
1100                 filp->f_pos = oclb.ctx.pos;
1101 #else
1102                 rc = fops->readdir(filp, &oclb, osd_stripe_dir_filldir);
1103 #endif
1104         } while (rc >= 0 && oclb.oclb_items > 0 && !oclb.oclb_found &&
1105                  filp->f_pos != LDISKFS_HTREE_EOF_64BIT);
1106         fops->release(inode, filp);
1107
1108 out:
1109         if (rc < 0)
1110                 CDEBUG(D_LFSCK,
1111                        "%s: cannot check LMV, ino = %lu/%u: rc = %d\n",
1112                        osd_ino2name(inode), inode->i_ino, inode->i_generation,
1113                        rc);
1114         else
1115                 rc = 0;
1116
1117         RETURN(rc);
1118 }
1119
1120 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
1121                           const struct lu_fid *fid,
1122                           const struct lu_object_conf *conf)
1123 {
1124         struct osd_thread_info *info;
1125         struct lu_device *ldev = obj->oo_dt.do_lu.lo_dev;
1126         struct osd_device *dev;
1127         struct osd_idmap_cache *oic;
1128         struct osd_inode_id *id;
1129         struct inode *inode = NULL;
1130         struct lustre_scrub *scrub;
1131         struct scrub_file *sf;
1132         __u32 flags = SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT | SS_AUTO_FULL;
1133         __u32 saved_ino;
1134         __u32 saved_gen;
1135         int result = 0;
1136         int rc1 = 0;
1137         bool remote = false;
1138         bool trusted = true;
1139         bool updated = false;
1140         bool checked = false;
1141
1142         ENTRY;
1143
1144         LINVRNT(osd_invariant(obj));
1145         LASSERT(obj->oo_inode == NULL);
1146         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID"\n", PFID(fid));
1147
1148         dev = osd_dev(ldev);
1149         scrub = &dev->od_scrub.os_scrub;
1150         sf = &scrub->os_file;
1151         info = osd_oti_get(env);
1152         LASSERT(info);
1153         oic = &info->oti_cache;
1154
1155         if (OBD_FAIL_CHECK(OBD_FAIL_SRV_ENOENT))
1156                 RETURN(-ENOENT);
1157
1158         /*
1159          * For the object is created as locking anchor, or for the object to
1160          * be created on disk. No need to osd_oi_lookup() at here because FID
1161          * shouldn't never be re-used, if it's really a duplicate FID from
1162          * unexpected reason, we should be able to detect it later by calling
1163          * do_create->osd_oi_insert().
1164          */
1165         if (conf && conf->loc_flags & LOC_F_NEW)
1166                 GOTO(out, result = 0);
1167
1168         /* Search order: 1. per-thread cache. */
1169         if (lu_fid_eq(fid, &oic->oic_fid) && likely(oic->oic_dev == dev)) {
1170                 id = &oic->oic_lid;
1171                 goto iget;
1172         }
1173
1174         id = &info->oti_id;
1175         if (!list_empty(&scrub->os_inconsistent_items)) {
1176                 /* Search order: 2. OI scrub pending list. */
1177                 result = osd_oii_lookup(dev, fid, id);
1178                 if (!result)
1179                         goto iget;
1180         }
1181
1182         /*
1183          * The OI mapping in the OI file can be updated by the OI scrub
1184          * when we locate the inode via FID. So it may be not trustable.
1185          */
1186         trusted = false;
1187
1188         /* Search order: 3. OI files. */
1189         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1190         if (result == -ENOENT) {
1191                 if (!(fid_is_norm(fid) || fid_is_igif(fid)) ||
1192                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
1193                     !ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
1194                                       sf->sf_oi_bitmap))
1195                         GOTO(out, result = 0);
1196
1197                 goto trigger;
1198         }
1199
1200         /* -ESTALE is returned if inode of OST object doesn't exist */
1201         if (result == -ESTALE &&
1202             fid_is_on_ost(info, dev, fid, OI_CHECK_FLD)) {
1203                 GOTO(out, result = 0);
1204         }
1205
1206         if (result)
1207                 GOTO(out, result);
1208
1209 iget:
1210         obj->oo_inode = NULL;
1211         /* for later passes through checks, not true on first pass */
1212         if (!IS_ERR_OR_NULL(inode))
1213                 iput(inode);
1214
1215         inode = osd_iget_check(info, dev, fid, id, trusted);
1216         if (!IS_ERR(inode)) {
1217                 obj->oo_inode = inode;
1218                 result = 0;
1219                 if (remote)
1220                         goto trigger;
1221
1222                 goto check_lma;
1223         }
1224
1225         result = PTR_ERR(inode);
1226         if (result == -ENOENT || result == -ESTALE)
1227                 GOTO(out, result = 0);
1228
1229         if (result != -EREMCHG)
1230                 GOTO(out, result);
1231
1232 trigger:
1233         /*
1234          * We still have chance to get the valid inode: for the
1235          * object which is referenced by remote name entry, the
1236          * object on the local MDT will be linked under the dir
1237          * of "/REMOTE_PARENT_DIR" with its FID string as name.
1238          *
1239          * We do not know whether the object for the given FID
1240          * is referenced by some remote name entry or not, and
1241          * especially for DNE II, a multiple-linked object may
1242          * have many name entries reside on many MDTs.
1243          *
1244          * To simplify the operation, OSD will not distinguish
1245          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
1246          * only happened for the RPC from other MDT during the
1247          * OI scrub, or for the client side RPC with FID only,
1248          * such as FID to path, or from old connected client.
1249          */
1250         if (!remote) {
1251                 rc1 = osd_lookup_in_remote_parent(info, dev, fid, id);
1252                 if (!rc1) {
1253                         remote = true;
1254                         trusted = true;
1255                         flags |= SS_AUTO_PARTIAL;
1256                         flags &= ~SS_AUTO_FULL;
1257                         goto iget;
1258                 }
1259         }
1260
1261         if (thread_is_running(&scrub->os_thread)) {
1262                 if (scrub->os_partial_scan && !scrub->os_in_join)
1263                         goto join;
1264
1265                 if (IS_ERR_OR_NULL(inode) || result) {
1266                         osd_oii_insert(dev, fid, id, result == -ENOENT);
1267                         GOTO(out, result = -EINPROGRESS);
1268                 }
1269
1270                 LASSERT(remote);
1271                 LASSERT(obj->oo_inode == inode);
1272
1273                 osd_oii_insert(dev, fid, id, true);
1274                 goto found;
1275         }
1276
1277         if (dev->od_auto_scrub_interval == AS_NEVER) {
1278                 if (!remote)
1279                         GOTO(out, result = -EREMCHG);
1280
1281                 LASSERT(!result);
1282                 LASSERT(obj->oo_inode == inode);
1283
1284                 osd_add_oi_cache(info, dev, id, fid);
1285                 goto found;
1286         }
1287
1288 join:
1289         rc1 = osd_scrub_start(env, dev, flags);
1290         LCONSOLE_WARN("%s: trigger OI scrub by RPC for the " DFID" with flags "
1291                       "0x%x, rc = %d\n", osd_name(dev), PFID(fid), flags, rc1);
1292         if (rc1 && rc1 != -EALREADY)
1293                 GOTO(out, result = -EREMCHG);
1294
1295         if (IS_ERR_OR_NULL(inode) || result) {
1296                 osd_oii_insert(dev, fid, id, result == -ENOENT);
1297                 GOTO(out, result = -EINPROGRESS);
1298         }
1299
1300         LASSERT(remote);
1301         LASSERT(obj->oo_inode == inode);
1302
1303         osd_oii_insert(dev, fid, id, true);
1304         goto found;
1305
1306 check_lma:
1307         checked = true;
1308         if (unlikely(obj->oo_header))
1309                 goto found;
1310
1311         result = osd_check_lma(env, obj);
1312         if (!result)
1313                 goto found;
1314
1315         LASSERTF(id->oii_ino == inode->i_ino &&
1316                  id->oii_gen == inode->i_generation,
1317                  "locate wrong inode for FID: "DFID", %u/%u => %ld/%u\n",
1318                  PFID(fid), id->oii_ino, id->oii_gen,
1319                  inode->i_ino, inode->i_generation);
1320
1321         saved_ino = inode->i_ino;
1322         saved_gen = inode->i_generation;
1323
1324         if (unlikely(result == -ENODATA)) {
1325                 /*
1326                  * If the OI scrub updated the OI mapping by race, it
1327                  * must be valid. Trust the inode that has no LMA EA.
1328                  */
1329                 if (updated)
1330                         goto found;
1331
1332                 result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1333                 if (!result) {
1334                         /*
1335                          * The OI mapping is still there, the inode is still
1336                          * valid. It is just becaues the inode has no LMA EA.
1337                          */
1338                         if (saved_ino == id->oii_ino &&
1339                             saved_gen == id->oii_gen)
1340                                 goto found;
1341
1342                         /*
1343                          * It is the OI scrub updated the OI mapping by race.
1344                          * The new OI mapping must be valid.
1345                          */
1346                         trusted = true;
1347                         updated = true;
1348                         goto iget;
1349                 }
1350
1351                 /*
1352                  * "result == -ENOENT" means that the OI mappinghas been
1353                  * removed by race, so the inode belongs to other object.
1354                  *
1355                  * Others error can be returned  directly.
1356                  */
1357                 if (result == -ENOENT) {
1358                         LASSERT(trusted);
1359
1360                         obj->oo_inode = NULL;
1361                         result = 0;
1362                 }
1363         }
1364
1365         if (result != -EREMCHG)
1366                 GOTO(out, result);
1367
1368         LASSERT(!updated);
1369
1370         /*
1371          * if two OST objects map to the same inode, and inode mode is
1372          * (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666), which means it's
1373          * reserved by precreate, and not written yet, in this case, don't
1374          * set inode for the object whose FID mismatch, so that it can create
1375          * inode and not block precreate.
1376          */
1377         if (fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) &&
1378             inode->i_mode == (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666)) {
1379                 obj->oo_inode = NULL;
1380                 GOTO(out, result = 0);
1381         }
1382
1383         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1384         /*
1385          * "result == -ENOENT" means the cached OI mapping has been removed
1386          * from the OI file by race, above inode belongs to other object.
1387          */
1388         if (result == -ENOENT) {
1389                 LASSERT(trusted);
1390
1391                 obj->oo_inode = NULL;
1392                 GOTO(out, result = 0);
1393         }
1394
1395         if (result)
1396                 GOTO(out, result);
1397
1398         if (saved_ino == id->oii_ino && saved_gen == id->oii_gen) {
1399                 result = -EREMCHG;
1400                 osd_scrub_refresh_mapping(info, dev, fid, id, DTO_INDEX_DELETE,
1401                                           true, 0, NULL);
1402                 goto trigger;
1403         }
1404
1405         /*
1406          * It is the OI scrub updated the OI mapping by race.
1407          * The new OI mapping must be valid.
1408          */
1409         trusted = true;
1410         updated = true;
1411         goto iget;
1412
1413 found:
1414         if (!checked) {
1415                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
1416                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
1417
1418                 result = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
1419                 if (!result) {
1420                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
1421                             dev->od_is_ost)
1422                                 obj->oo_pfid_in_lma = 1;
1423                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
1424                             !dev->od_is_ost)
1425                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
1426                 } else if (result != -ENODATA) {
1427                         GOTO(out, result);
1428                 }
1429         }
1430
1431         obj->oo_compat_dot_created = 1;
1432         obj->oo_compat_dotdot_created = 1;
1433
1434         if (S_ISDIR(inode->i_mode) &&
1435             (flags & SS_AUTO_PARTIAL || sf->sf_status == SS_SCANNING))
1436                 osd_check_lmv(info, dev, inode);
1437
1438         result = osd_attach_jinode(inode);
1439         if (result)
1440                 GOTO(out, result);
1441
1442         if (!ldiskfs_pdo)
1443                 GOTO(out, result = 0);
1444
1445         LASSERT(!obj->oo_hl_head);
1446         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1447
1448         GOTO(out, result = (!obj->oo_hl_head ? -ENOMEM : 0));
1449
1450 out:
1451         if (result || !obj->oo_inode) {
1452                 if (!IS_ERR_OR_NULL(inode))
1453                         iput(inode);
1454
1455                 obj->oo_inode = NULL;
1456                 if (trusted)
1457                         fid_zero(&oic->oic_fid);
1458         }
1459
1460         LINVRNT(osd_invariant(obj));
1461         return result;
1462 }
1463
1464 /*
1465  * Concurrency: shouldn't matter.
1466  */
1467 static void osd_object_init0(struct osd_object *obj)
1468 {
1469         LASSERT(obj->oo_inode != NULL);
1470         obj->oo_dt.do_body_ops = &osd_body_ops;
1471         obj->oo_dt.do_lu.lo_header->loh_attr |=
1472                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
1473 }
1474
1475 /*
1476  * Concurrency: no concurrent access is possible that early in object
1477  * life-cycle.
1478  */
1479 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
1480                            const struct lu_object_conf *conf)
1481 {
1482         struct osd_object *obj = osd_obj(l);
1483         int result;
1484
1485         LINVRNT(osd_invariant(obj));
1486
1487         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
1488                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
1489                 l->lo_header->loh_attr |= LOHA_EXISTS;
1490                 return 0;
1491         }
1492
1493         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
1494         obj->oo_dt.do_body_ops = &osd_body_ops_new;
1495         if (result == 0 && obj->oo_inode != NULL) {
1496                 struct osd_thread_info *oti = osd_oti_get(env);
1497                 struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
1498
1499                 osd_object_init0(obj);
1500                 if (unlikely(obj->oo_header))
1501                         return 0;
1502
1503                 result = osd_get_lma(oti, obj->oo_inode,
1504                                      &oti->oti_obj_dentry, loa);
1505                 if (!result) {
1506                         /*
1507                          * Convert LMAI flags to lustre LMA flags
1508                          * and cache it to oo_lma_flags
1509                          */
1510                         obj->oo_lma_flags =
1511                                 lma_to_lustre_flags(loa->loa_lma.lma_incompat);
1512                 } else if (result == -ENODATA) {
1513                         result = 0;
1514                 }
1515         }
1516
1517         LINVRNT(osd_invariant(obj));
1518         return result;
1519 }
1520
1521 /*
1522  * The first part of oxe_buf is xattr name, and is '\0' terminated.
1523  * The left part is for value, binary mode.
1524  */
1525 struct osd_xattr_entry {
1526         struct list_head        oxe_list;
1527         size_t                  oxe_len;
1528         size_t                  oxe_namelen;
1529         bool                    oxe_exist;
1530         struct rcu_head         oxe_rcu;
1531         char                    oxe_buf[0];
1532 };
1533
1534 static int osd_oxc_get(struct osd_object *obj, const char *name,
1535                        struct lu_buf *buf)
1536 {
1537         struct osd_xattr_entry *tmp;
1538         struct osd_xattr_entry *oxe = NULL;
1539         size_t namelen = strlen(name);
1540         int rc;
1541
1542         ENTRY;
1543
1544         rcu_read_lock();
1545         list_for_each_entry_rcu(tmp, &obj->oo_xattr_list, oxe_list) {
1546                 if (namelen == tmp->oxe_namelen &&
1547                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1548                         oxe = tmp;
1549                         break;
1550                 }
1551         }
1552
1553         if (oxe == NULL)
1554                 GOTO(out, rc = -ENOENT);
1555
1556         if (!oxe->oxe_exist)
1557                 GOTO(out, rc = -ENODATA);
1558
1559         /* vallen */
1560         rc = oxe->oxe_len - sizeof(*oxe) - oxe->oxe_namelen - 1;
1561         LASSERT(rc > 0);
1562
1563         if (buf->lb_buf == NULL)
1564                 GOTO(out, rc);
1565
1566         if (buf->lb_len < rc)
1567                 GOTO(out, rc = -ERANGE);
1568
1569         memcpy(buf->lb_buf, &oxe->oxe_buf[namelen + 1], rc);
1570         EXIT;
1571 out:
1572         rcu_read_unlock();
1573
1574         return rc;
1575 }
1576
1577 static void osd_oxc_free(struct rcu_head *head)
1578 {
1579         struct osd_xattr_entry *oxe;
1580
1581         oxe = container_of(head, struct osd_xattr_entry, oxe_rcu);
1582         OBD_FREE(oxe, oxe->oxe_len);
1583 }
1584
1585 static void osd_oxc_add(struct osd_object *obj, const char *name,
1586                         const char *buf, int buflen)
1587 {
1588         struct osd_xattr_entry *oxe;
1589         struct osd_xattr_entry *old = NULL;
1590         struct osd_xattr_entry *tmp;
1591         size_t namelen = strlen(name);
1592         size_t len = sizeof(*oxe) + namelen + 1 + buflen;
1593
1594         OBD_ALLOC(oxe, len);
1595         if (oxe == NULL)
1596                 return;
1597
1598         INIT_LIST_HEAD(&oxe->oxe_list);
1599         oxe->oxe_len = len;
1600         oxe->oxe_namelen = namelen;
1601         memcpy(oxe->oxe_buf, name, namelen);
1602         if (buflen > 0) {
1603                 LASSERT(buf != NULL);
1604                 memcpy(oxe->oxe_buf + namelen + 1, buf, buflen);
1605                 oxe->oxe_exist = true;
1606         } else {
1607                 oxe->oxe_exist = false;
1608         }
1609
1610         /* this should be rarely called, just remove old and add new */
1611         spin_lock(&obj->oo_guard);
1612         list_for_each_entry(tmp, &obj->oo_xattr_list, oxe_list) {
1613                 if (namelen == tmp->oxe_namelen &&
1614                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1615                         old = tmp;
1616                         break;
1617                 }
1618         }
1619         if (old != NULL) {
1620                 list_replace_rcu(&old->oxe_list, &oxe->oxe_list);
1621                 call_rcu(&old->oxe_rcu, osd_oxc_free);
1622         } else {
1623                 list_add_tail_rcu(&oxe->oxe_list, &obj->oo_xattr_list);
1624         }
1625         spin_unlock(&obj->oo_guard);
1626 }
1627
1628 static void osd_oxc_del(struct osd_object *obj, const char *name)
1629 {
1630         struct osd_xattr_entry *oxe;
1631         size_t namelen = strlen(name);
1632
1633         spin_lock(&obj->oo_guard);
1634         list_for_each_entry(oxe, &obj->oo_xattr_list, oxe_list) {
1635                 if (namelen == oxe->oxe_namelen &&
1636                     strncmp(name, oxe->oxe_buf, namelen) == 0) {
1637                         list_del_rcu(&oxe->oxe_list);
1638                         call_rcu(&oxe->oxe_rcu, osd_oxc_free);
1639                         break;
1640                 }
1641         }
1642         spin_unlock(&obj->oo_guard);
1643 }
1644
1645 static void osd_oxc_fini(struct osd_object *obj)
1646 {
1647         struct osd_xattr_entry *oxe, *next;
1648
1649         list_for_each_entry_safe(oxe, next, &obj->oo_xattr_list, oxe_list) {
1650                 list_del(&oxe->oxe_list);
1651                 OBD_FREE(oxe, oxe->oxe_len);
1652         }
1653 }
1654
1655 /*
1656  * Concurrency: no concurrent access is possible that late in object
1657  * life-cycle.
1658  */
1659 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
1660 {
1661         struct osd_object *obj = osd_obj(l);
1662         struct lu_object_header *h = obj->oo_header;
1663
1664         LINVRNT(osd_invariant(obj));
1665
1666         osd_oxc_fini(obj);
1667         dt_object_fini(&obj->oo_dt);
1668         if (obj->oo_hl_head != NULL)
1669                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1670         OBD_FREE_PTR(obj);
1671         if (unlikely(h)) {
1672                 lu_object_header_fini(h);
1673                 OBD_FREE_PTR(h);
1674         }
1675 }
1676
1677 /*
1678  * Concurrency: no concurrent access is possible that late in object
1679  * life-cycle.
1680  */
1681 static void osd_index_fini(struct osd_object *o)
1682 {
1683         struct iam_container *bag;
1684
1685         if (o->oo_dir != NULL) {
1686                 bag = &o->oo_dir->od_container;
1687                 if (o->oo_inode != NULL) {
1688                         if (bag->ic_object == o->oo_inode)
1689                                 iam_container_fini(bag);
1690                 }
1691                 OBD_FREE_PTR(o->oo_dir);
1692                 o->oo_dir = NULL;
1693         }
1694 }
1695
1696 /*
1697  * Concurrency: no concurrent access is possible that late in object
1698  * life-cycle (for all existing callers, that is. New callers have to provide
1699  * their own locking.)
1700  */
1701 static int osd_inode_unlinked(const struct inode *inode)
1702 {
1703         return inode->i_nlink == 0;
1704 }
1705
1706 enum {
1707         OSD_TXN_OI_DELETE_CREDITS    = 20,
1708         OSD_TXN_INODE_DELETE_CREDITS = 20
1709 };
1710
1711 /*
1712  * Journal
1713  */
1714
1715 #if OSD_THANDLE_STATS
1716 /**
1717  * Set time when the handle is allocated
1718  */
1719 static void osd_th_alloced(struct osd_thandle *oth)
1720 {
1721         oth->oth_alloced = ktime_get();
1722 }
1723
1724 /**
1725  * Set time when the handle started
1726  */
1727 static void osd_th_started(struct osd_thandle *oth)
1728 {
1729         oth->oth_started = ktime_get();
1730 }
1731
1732 /**
1733  * Check whether the we deal with this handle for too long.
1734  */
1735 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
1736                                 ktime_t alloced, ktime_t started,
1737                                 ktime_t closed)
1738 {
1739         ktime_t now = ktime_get();
1740
1741         LASSERT(dev != NULL);
1742
1743         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
1744                             ktime_us_delta(started, alloced));
1745         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
1746                             ktime_us_delta(closed, started));
1747         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
1748                             ktime_us_delta(now, closed));
1749
1750         if (ktime_before(ktime_add_ns(alloced, 30 * NSEC_PER_SEC), now)) {
1751                 CWARN("transaction handle %p was open for too long: now %lld, alloced %lld, started %lld, closed %lld\n",
1752                                 oth, now, alloced, started, closed);
1753                 libcfs_debug_dumpstack(NULL);
1754         }
1755 }
1756
1757 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
1758 {                                                                       \
1759         ktime_t __closed = ktime_get();                                 \
1760         ktime_t __alloced = oth->oth_alloced;                           \
1761         ktime_t __started = oth->oth_started;                           \
1762                                                                         \
1763         expr;                                                           \
1764         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
1765 }
1766
1767 #else /* OSD_THANDLE_STATS */
1768
1769 #define osd_th_alloced(h)                  do {} while(0)
1770 #define osd_th_started(h)                  do {} while(0)
1771 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
1772
1773 #endif /* OSD_THANDLE_STATS */
1774
1775 /*
1776  * Concurrency: doesn't access mutable data.
1777  */
1778 static int osd_param_is_not_sane(const struct osd_device *dev,
1779                                  const struct thandle *th)
1780 {
1781         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
1782
1783         return oh->ot_credits > osd_transaction_size(dev);
1784 }
1785
1786 /*
1787  * Concurrency: shouldn't matter.
1788  */
1789 static void osd_trans_commit_cb(struct super_block *sb,
1790                                 struct ldiskfs_journal_cb_entry *jcb, int error)
1791 {
1792         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
1793         struct thandle *th = &oh->ot_super;
1794         struct lu_device *lud = &th->th_dev->dd_lu_dev;
1795         struct dt_txn_commit_cb *dcb, *tmp;
1796
1797         LASSERT(oh->ot_handle == NULL);
1798
1799         if (error)
1800                 CERROR("transaction @0x%p commit error: %d\n", th, error);
1801
1802         /* call per-transaction callbacks if any */
1803         list_for_each_entry_safe(dcb, tmp, &oh->ot_commit_dcb_list,
1804                                  dcb_linkage) {
1805                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1806                          "commit callback entry: magic=%x name='%s'\n",
1807                          dcb->dcb_magic, dcb->dcb_name);
1808                 list_del_init(&dcb->dcb_linkage);
1809                 dcb->dcb_func(NULL, th, dcb, error);
1810         }
1811
1812         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
1813         lu_device_put(lud);
1814         th->th_dev = NULL;
1815
1816         OBD_FREE_PTR(oh);
1817 }
1818
1819 #ifndef HAVE_SB_START_WRITE
1820 # define sb_start_write(sb) do {} while (0)
1821 # define sb_end_write(sb) do {} while (0)
1822 #endif
1823
1824 static struct thandle *osd_trans_create(const struct lu_env *env,
1825                                         struct dt_device *d)
1826 {
1827         struct osd_thread_info *oti = osd_oti_get(env);
1828         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1829         struct osd_thandle *oh;
1830         struct thandle *th;
1831
1832         ENTRY;
1833
1834         if (d->dd_rdonly) {
1835                 CERROR("%s: someone try to start transaction under "
1836                        "readonly mode, should be disabled.\n",
1837                        osd_name(osd_dt_dev(d)));
1838                 dump_stack();
1839                 RETURN(ERR_PTR(-EROFS));
1840         }
1841
1842         /* on pending IO in this thread should left from prev. request */
1843         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
1844
1845         sb_start_write(osd_sb(osd_dt_dev(d)));
1846
1847         OBD_ALLOC_GFP(oh, sizeof(*oh), GFP_NOFS);
1848         if (!oh) {
1849                 sb_end_write(osd_sb(osd_dt_dev(d)));
1850                 RETURN(ERR_PTR(-ENOMEM));
1851         }
1852
1853         oh->ot_quota_trans = &oti->oti_quota_trans;
1854         memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
1855         th = &oh->ot_super;
1856         th->th_dev = d;
1857         th->th_result = 0;
1858         oh->ot_credits = 0;
1859         INIT_LIST_HEAD(&oh->ot_commit_dcb_list);
1860         INIT_LIST_HEAD(&oh->ot_stop_dcb_list);
1861         INIT_LIST_HEAD(&oh->ot_trunc_locks);
1862         osd_th_alloced(oh);
1863
1864         memset(oti->oti_declare_ops, 0,
1865                sizeof(oti->oti_declare_ops));
1866         memset(oti->oti_declare_ops_cred, 0,
1867                sizeof(oti->oti_declare_ops_cred));
1868         memset(oti->oti_declare_ops_used, 0,
1869                sizeof(oti->oti_declare_ops_used));
1870
1871         oti->oti_ins_cache_depth++;
1872
1873         RETURN(th);
1874 }
1875
1876 void osd_trans_dump_creds(const struct lu_env *env, struct thandle *th)
1877 {
1878         struct osd_thread_info *oti = osd_oti_get(env);
1879         struct osd_thandle *oh;
1880
1881         oh = container_of0(th, struct osd_thandle, ot_super);
1882         LASSERT(oh != NULL);
1883
1884         CWARN("  create: %u/%u/%u, destroy: %u/%u/%u\n",
1885               oti->oti_declare_ops[OSD_OT_CREATE],
1886               oti->oti_declare_ops_cred[OSD_OT_CREATE],
1887               oti->oti_declare_ops_used[OSD_OT_CREATE],
1888               oti->oti_declare_ops[OSD_OT_DESTROY],
1889               oti->oti_declare_ops_cred[OSD_OT_DESTROY],
1890               oti->oti_declare_ops_used[OSD_OT_DESTROY]);
1891         CWARN("  attr_set: %u/%u/%u, xattr_set: %u/%u/%u\n",
1892               oti->oti_declare_ops[OSD_OT_ATTR_SET],
1893               oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1894               oti->oti_declare_ops_used[OSD_OT_ATTR_SET],
1895               oti->oti_declare_ops[OSD_OT_XATTR_SET],
1896               oti->oti_declare_ops_cred[OSD_OT_XATTR_SET],
1897               oti->oti_declare_ops_used[OSD_OT_XATTR_SET]);
1898         CWARN("  write: %u/%u/%u, punch: %u/%u/%u, quota %u/%u/%u\n",
1899               oti->oti_declare_ops[OSD_OT_WRITE],
1900               oti->oti_declare_ops_cred[OSD_OT_WRITE],
1901               oti->oti_declare_ops_used[OSD_OT_WRITE],
1902               oti->oti_declare_ops[OSD_OT_PUNCH],
1903               oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1904               oti->oti_declare_ops_used[OSD_OT_PUNCH],
1905               oti->oti_declare_ops[OSD_OT_QUOTA],
1906               oti->oti_declare_ops_cred[OSD_OT_QUOTA],
1907               oti->oti_declare_ops_used[OSD_OT_QUOTA]);
1908         CWARN("  insert: %u/%u/%u, delete: %u/%u/%u\n",
1909               oti->oti_declare_ops[OSD_OT_INSERT],
1910               oti->oti_declare_ops_cred[OSD_OT_INSERT],
1911               oti->oti_declare_ops_used[OSD_OT_INSERT],
1912               oti->oti_declare_ops[OSD_OT_DELETE],
1913               oti->oti_declare_ops_cred[OSD_OT_DELETE],
1914               oti->oti_declare_ops_used[OSD_OT_DELETE]);
1915         CWARN("  ref_add: %u/%u/%u, ref_del: %u/%u/%u\n",
1916               oti->oti_declare_ops[OSD_OT_REF_ADD],
1917               oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1918               oti->oti_declare_ops_used[OSD_OT_REF_ADD],
1919               oti->oti_declare_ops[OSD_OT_REF_DEL],
1920               oti->oti_declare_ops_cred[OSD_OT_REF_DEL],
1921               oti->oti_declare_ops_used[OSD_OT_REF_DEL]);
1922 }
1923
1924 /*
1925  * Concurrency: shouldn't matter.
1926  */
1927 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
1928                            struct thandle *th)
1929 {
1930         struct osd_thread_info *oti = osd_oti_get(env);
1931         struct osd_device *dev = osd_dt_dev(d);
1932         handle_t *jh;
1933         struct osd_thandle *oh;
1934         int rc;
1935
1936         ENTRY;
1937
1938         LASSERT(current->journal_info == NULL);
1939
1940         oh = container_of0(th, struct osd_thandle, ot_super);
1941         LASSERT(oh != NULL);
1942         LASSERT(oh->ot_handle == NULL);
1943
1944         rc = dt_txn_hook_start(env, d, th);
1945         if (rc != 0)
1946                 GOTO(out, rc);
1947
1948         if (unlikely(osd_param_is_not_sane(dev, th))) {
1949                 static unsigned long last_printed;
1950                 static int last_credits;
1951
1952                 /*
1953                  * don't make noise on a tiny testing systems
1954                  * actual credits misuse will be caught anyway
1955                  */
1956                 if (last_credits != oh->ot_credits &&
1957                     time_after(jiffies, last_printed +
1958                                msecs_to_jiffies(60 * MSEC_PER_SEC)) &&
1959                     osd_transaction_size(dev) > 512) {
1960                         CWARN("%s: credits %u > trans_max %u\n", osd_name(dev),
1961                               oh->ot_credits, osd_transaction_size(dev));
1962                         osd_trans_dump_creds(env, th);
1963                         libcfs_debug_dumpstack(NULL);
1964                         last_credits = oh->ot_credits;
1965                         last_printed = jiffies;
1966                 }
1967                 /*
1968                  * XXX Limit the credits to 'max_transaction_buffers', and
1969                  *     let the underlying filesystem to catch the error if
1970                  *     we really need so many credits.
1971                  *
1972                  *     This should be removed when we can calculate the
1973                  *     credits precisely.
1974                  */
1975                 oh->ot_credits = osd_transaction_size(dev);
1976         } else if (ldiskfs_track_declares_assert != 0) {
1977                 /*
1978                  * reserve few credits to prevent an assertion in JBD
1979                  * our debugging mechanism will be able to detected
1980                  * overuse. this can help to debug single-update
1981                  * transactions
1982                  */
1983                 oh->ot_credits += 10;
1984                 if (unlikely(osd_param_is_not_sane(dev, th)))
1985                         oh->ot_credits = osd_transaction_size(dev);
1986         }
1987
1988         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_TXN_START))
1989                 GOTO(out, rc = -EIO);
1990
1991         /*
1992          * XXX temporary stuff. Some abstraction layer should
1993          * be used.
1994          */
1995         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
1996         osd_th_started(oh);
1997         if (!IS_ERR(jh)) {
1998                 oh->ot_handle = jh;
1999                 LASSERT(oti->oti_txns == 0);
2000
2001                 lu_device_get(&d->dd_lu_dev);
2002                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
2003                               "osd-tx", th);
2004                 oti->oti_txns++;
2005                 rc = 0;
2006         } else {
2007                 rc = PTR_ERR(jh);
2008         }
2009 out:
2010         RETURN(rc);
2011 }
2012
2013 static int osd_seq_exists(const struct lu_env *env,
2014                           struct osd_device *osd, u64 seq)
2015 {
2016         struct lu_seq_range *range = &osd_oti_get(env)->oti_seq_range;
2017         struct seq_server_site *ss = osd_seq_site(osd);
2018         int rc;
2019
2020         ENTRY;
2021
2022         LASSERT(ss != NULL);
2023         LASSERT(ss->ss_server_fld != NULL);
2024
2025         rc = osd_fld_lookup(env, osd, seq, range);
2026         if (rc != 0) {
2027                 if (rc != -ENOENT)
2028                         CERROR("%s: can't lookup FLD sequence %#llx: rc = %d\n",
2029                                osd_name(osd), seq, rc);
2030                 RETURN(0);
2031         }
2032
2033         RETURN(ss->ss_node_id == range->lsr_index);
2034 }
2035
2036 static void osd_trans_stop_cb(struct osd_thandle *oth, int result)
2037 {
2038         struct dt_txn_commit_cb *dcb;
2039         struct dt_txn_commit_cb *tmp;
2040
2041         /* call per-transaction stop callbacks if any */
2042         list_for_each_entry_safe(dcb, tmp, &oth->ot_stop_dcb_list,
2043                                  dcb_linkage) {
2044                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
2045                          "commit callback entry: magic=%x name='%s'\n",
2046                          dcb->dcb_magic, dcb->dcb_name);
2047                 list_del_init(&dcb->dcb_linkage);
2048                 dcb->dcb_func(NULL, &oth->ot_super, dcb, result);
2049         }
2050 }
2051
2052 /*
2053  * Concurrency: shouldn't matter.
2054  */
2055 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
2056                           struct thandle *th)
2057 {
2058         struct osd_thread_info *oti = osd_oti_get(env);
2059         struct osd_thandle *oh;
2060         struct osd_iobuf *iobuf = &oti->oti_iobuf;
2061         struct osd_device *osd = osd_dt_dev(th->th_dev);
2062         struct qsd_instance *qsd = osd_def_qsd(osd);
2063         struct lquota_trans *qtrans;
2064         struct list_head truncates = LIST_HEAD_INIT(truncates);
2065         int rc = 0, remove_agents = 0;
2066
2067         ENTRY;
2068
2069         oh = container_of0(th, struct osd_thandle, ot_super);
2070
2071         remove_agents = oh->ot_remove_agents;
2072
2073         qtrans = oh->ot_quota_trans;
2074         oh->ot_quota_trans = NULL;
2075
2076         /* move locks to local list, stop tx, execute truncates */
2077         list_splice(&oh->ot_trunc_locks, &truncates);
2078
2079         if (oh->ot_handle != NULL) {
2080                 int rc2;
2081
2082                 handle_t *hdl = oh->ot_handle;
2083
2084                 /*
2085                  * add commit callback
2086                  * notice we don't do this in osd_trans_start()
2087                  * as underlying transaction can change during truncate
2088                  */
2089                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
2090                                              &oh->ot_jcb);
2091
2092                 LASSERT(oti->oti_txns == 1);
2093                 oti->oti_txns--;
2094
2095                 rc = dt_txn_hook_stop(env, th);
2096                 if (rc != 0)
2097                         CERROR("%s: failed in transaction hook: rc = %d\n",
2098                                osd_name(osd), rc);
2099
2100                 osd_trans_stop_cb(oh, rc);
2101                 /* hook functions might modify th_sync */
2102                 hdl->h_sync = th->th_sync;
2103
2104                 oh->ot_handle = NULL;
2105                 OSD_CHECK_SLOW_TH(oh, osd, rc2 = ldiskfs_journal_stop(hdl));
2106                 if (rc2 != 0)
2107                         CERROR("%s: failed to stop transaction: rc = %d\n",
2108                                osd_name(osd), rc2);
2109                 if (!rc)
2110                         rc = rc2;
2111
2112                 osd_process_truncates(&truncates);
2113         } else {
2114                 osd_trans_stop_cb(oh, th->th_result);
2115                 OBD_FREE_PTR(oh);
2116         }
2117
2118         osd_trunc_unlock_all(env, &truncates);
2119
2120         /* inform the quota slave device that the transaction is stopping */
2121         qsd_op_end(env, qsd, qtrans);
2122
2123         /*
2124          * as we want IO to journal and data IO be concurrent, we don't block
2125          * awaiting data IO completion in osd_do_bio(), instead we wait here
2126          * once transaction is submitted to the journal. all reqular requests
2127          * don't do direct IO (except read/write), thus this wait_event becomes
2128          * no-op for them.
2129          *
2130          * IMPORTANT: we have to wait till any IO submited by the thread is
2131          * completed otherwise iobuf may be corrupted by different request
2132          */
2133         wait_event(iobuf->dr_wait,
2134                        atomic_read(&iobuf->dr_numreqs) == 0);
2135         osd_fini_iobuf(osd, iobuf);
2136         if (!rc)
2137                 rc = iobuf->dr_error;
2138
2139         if (unlikely(remove_agents != 0))
2140                 osd_process_scheduled_agent_removals(env, osd);
2141
2142         LASSERT(oti->oti_ins_cache_depth > 0);
2143         oti->oti_ins_cache_depth--;
2144         /* reset OI cache for safety */
2145         if (oti->oti_ins_cache_depth == 0)
2146                 oti->oti_ins_cache_used = 0;
2147
2148         sb_end_write(osd_sb(osd));
2149
2150         RETURN(rc);
2151 }
2152
2153 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
2154 {
2155         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
2156                                                ot_super);
2157
2158         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
2159         LASSERT(&dcb->dcb_func != NULL);
2160         if (dcb->dcb_flags & DCB_TRANS_STOP)
2161                 list_add(&dcb->dcb_linkage, &oh->ot_stop_dcb_list);
2162         else
2163                 list_add(&dcb->dcb_linkage, &oh->ot_commit_dcb_list);
2164
2165         return 0;
2166 }
2167
2168 /*
2169  * Called just before object is freed. Releases all resources except for
2170  * object itself (that is released by osd_object_free()).
2171  *
2172  * Concurrency: no concurrent access is possible that late in object
2173  * life-cycle.
2174  */
2175 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
2176 {
2177         struct osd_object *obj = osd_obj(l);
2178         struct qsd_instance *qsd = osd_def_qsd(osd_obj2dev(obj));
2179         struct inode *inode = obj->oo_inode;
2180         __u64 projid;
2181         qid_t uid;
2182         qid_t gid;
2183
2184         LINVRNT(osd_invariant(obj));
2185
2186         /*
2187          * If object is unlinked remove fid->ino mapping from object index.
2188          */
2189
2190         osd_index_fini(obj);
2191
2192         if (!inode)
2193                 return;
2194
2195         if (osd_has_index(obj) &&  obj->oo_dt.do_index_ops == &osd_index_iam_ops)
2196                 ldiskfs_set_inode_flag(inode, LDISKFS_INODE_JOURNAL_DATA);
2197
2198         uid = i_uid_read(inode);
2199         gid = i_gid_read(inode);
2200         projid = i_projid_read(inode);
2201
2202         obj->oo_inode = NULL;
2203         iput(inode);
2204
2205         /* do not rebalance quota if the caller needs to release memory
2206          * otherwise qsd_refresh_usage() may went into a new ldiskfs
2207          * transaction and risk to deadlock - LU-12178 */
2208         if (current->flags & (PF_MEMALLOC | PF_KSWAPD))
2209                 return;
2210
2211         if (!obj->oo_header && qsd) {
2212                 struct osd_thread_info *info = osd_oti_get(env);
2213                 struct lquota_id_info *qi = &info->oti_qi;
2214
2215                 /* Release granted quota to master if necessary */
2216                 qi->lqi_id.qid_uid = uid;
2217                 qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
2218
2219                 qi->lqi_id.qid_uid = gid;
2220                 qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
2221
2222                 qi->lqi_id.qid_uid = projid;
2223                 qsd_op_adjust(env, qsd, &qi->lqi_id, PRJQUOTA);
2224         }
2225 }
2226
2227 /*
2228  * Concurrency: ->loo_object_release() is called under site spin-lock.
2229  */
2230 static void osd_object_release(const struct lu_env *env,
2231                                struct lu_object *l)
2232 {
2233         struct osd_object *o = osd_obj(l);
2234
2235         /*
2236          * nobody should be releasing a non-destroyed object with nlink=0
2237          * the API allows this, but ldiskfs doesn't like and then report
2238          * this inode as deleted
2239          */
2240         LASSERT(!(o->oo_destroyed == 0 && o->oo_inode &&
2241                   o->oo_inode->i_nlink == 0));
2242 }
2243
2244 /*
2245  * Concurrency: shouldn't matter.
2246  */
2247 static int osd_object_print(const struct lu_env *env, void *cookie,
2248                             lu_printer_t p, const struct lu_object *l)
2249 {
2250         struct osd_object *o = osd_obj(l);
2251         struct iam_descr *d;
2252
2253         if (o->oo_dir != NULL)
2254                 d = o->oo_dir->od_container.ic_descr;
2255         else
2256                 d = NULL;
2257         return (*p)(env, cookie,
2258                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
2259                     o, o->oo_inode,
2260                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
2261                     o->oo_inode ? o->oo_inode->i_generation : 0,
2262                     d ? d->id_ops->id_name : "plain");
2263 }
2264
2265 /*
2266  * Concurrency: shouldn't matter.
2267  */
2268 int osd_statfs(const struct lu_env *env, struct dt_device *d,
2269                 struct obd_statfs *sfs)
2270 {
2271         struct osd_device *osd = osd_dt_dev(d);
2272         struct super_block *sb = osd_sb(osd);
2273         struct kstatfs *ksfs;
2274         __u64 reserved;
2275         int result = 0;
2276
2277         if (unlikely(osd->od_mnt == NULL))
2278                 return -EINPROGRESS;
2279
2280         /* osd_lproc.c call this without env, allocate ksfs for that case */
2281         if (unlikely(env == NULL)) {
2282                 OBD_ALLOC_PTR(ksfs);
2283                 if (ksfs == NULL)
2284                         return -ENOMEM;
2285         } else {
2286                 ksfs = &osd_oti_get(env)->oti_ksfs;
2287         }
2288
2289         result = sb->s_op->statfs(sb->s_root, ksfs);
2290         if (result)
2291                 goto out;
2292
2293         statfs_pack(sfs, ksfs);
2294         if (unlikely(sb->s_flags & MS_RDONLY))
2295                 sfs->os_state |= OS_STATE_READONLY;
2296
2297         sfs->os_state |= osd->od_nonrotational ? OS_STATE_NONROT : 0;
2298
2299         if (ldiskfs_has_feature_extents(sb))
2300                 sfs->os_maxbytes = sb->s_maxbytes;
2301         else
2302                 sfs->os_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2303
2304         /*
2305          * Reserve some space so to avoid fragmenting the filesystem too much.
2306          * Fragmentation not only impacts performance, but can also increase
2307          * metadata overhead significantly, causing grant calculation to be
2308          * wrong.
2309          *
2310          * Reserve 0.78% of total space, at least 8MB for small filesystems.
2311          */
2312         CLASSERT(OSD_STATFS_RESERVED > LDISKFS_MAX_BLOCK_SIZE);
2313         reserved = OSD_STATFS_RESERVED >> sb->s_blocksize_bits;
2314         if (likely(sfs->os_blocks >= reserved << OSD_STATFS_RESERVED_SHIFT))
2315                 reserved = sfs->os_blocks >> OSD_STATFS_RESERVED_SHIFT;
2316
2317         sfs->os_blocks -= reserved;
2318         sfs->os_bfree  -= min(reserved, sfs->os_bfree);
2319         sfs->os_bavail -= min(reserved, sfs->os_bavail);
2320
2321 out:
2322         if (unlikely(env == NULL))
2323                 OBD_FREE_PTR(ksfs);
2324         return result;
2325 }
2326
2327 /**
2328  * Estimate space needed for file creations. We assume the largest filename
2329  * which is 2^64 - 1, hence a filename of 20 chars.
2330  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
2331  */
2332 #ifdef __LDISKFS_DIR_REC_LEN
2333 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
2334 #else
2335 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
2336 #endif
2337
2338 /*
2339  * Concurrency: doesn't access mutable data.
2340  */
2341 static void osd_conf_get(const struct lu_env *env,
2342                          const struct dt_device *dev,
2343                          struct dt_device_param *param)
2344 {
2345         struct osd_device *d = osd_dt_dev(dev);
2346         struct super_block *sb = osd_sb(d);
2347         struct blk_integrity *bi = bdev_get_integrity(sb->s_bdev);
2348         const char *name;
2349         int ea_overhead;
2350
2351         /*
2352          * XXX should be taken from not-yet-existing fs abstraction layer.
2353          */
2354         param->ddp_max_name_len = LDISKFS_NAME_LEN;
2355         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
2356         param->ddp_symlink_max  = sb->s_blocksize;
2357         param->ddp_mount_type   = LDD_MT_LDISKFS;
2358         if (ldiskfs_has_feature_extents(sb))
2359                 param->ddp_maxbytes = sb->s_maxbytes;
2360         else
2361                 param->ddp_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2362         /*
2363          * inode are statically allocated, so per-inode space consumption
2364          * is the space consumed by the directory entry
2365          */
2366         param->ddp_inodespace     = PER_OBJ_USAGE;
2367         /*
2368          * EXT_INIT_MAX_LEN is the theoretical maximum extent size (32k blocks
2369          * is 128MB) which is unlikely to be hit in real life. Report a smaller
2370          * maximum length to not under-count the actual number of extents
2371          * needed for writing a file if there are sub-optimal block allocations.
2372          */
2373         param->ddp_max_extent_blks = EXT_INIT_MAX_LEN >> 1;
2374         /* worst-case extent insertion metadata overhead */
2375         param->ddp_extent_tax = 6 * LDISKFS_BLOCK_SIZE(sb);
2376         param->ddp_mntopts = 0;
2377         if (test_opt(sb, XATTR_USER))
2378                 param->ddp_mntopts |= MNTOPT_USERXATTR;
2379         if (test_opt(sb, POSIX_ACL))
2380                 param->ddp_mntopts |= MNTOPT_ACL;
2381
2382         /*
2383          * LOD might calculate the max stripe count based on max_ea_size,
2384          * so we need take account in the overhead as well,
2385          * xattr_header + magic + xattr_entry_head
2386          */
2387         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
2388                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
2389
2390 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
2391         if (ldiskfs_has_feature_ea_inode(sb))
2392                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
2393                                                                 ea_overhead;
2394         else
2395 #endif
2396                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
2397
2398         if (param->ddp_max_ea_size > OSD_MAX_EA_SIZE)
2399                 param->ddp_max_ea_size = OSD_MAX_EA_SIZE;
2400
2401         /*
2402          * Preferred RPC size for efficient disk IO.  4MB shows good
2403          * all-around performance for ldiskfs, but use bigalloc chunk size
2404          * by default if larger.
2405          */
2406 #if defined(LDISKFS_CLUSTER_SIZE)
2407         if (LDISKFS_CLUSTER_SIZE(sb) > DT_DEF_BRW_SIZE)
2408                 param->ddp_brw_size = LDISKFS_CLUSTER_SIZE(sb);
2409         else
2410 #endif
2411                 param->ddp_brw_size = DT_DEF_BRW_SIZE;
2412
2413         param->ddp_t10_cksum_type = 0;
2414         if (bi) {
2415                 unsigned short interval = blk_integrity_interval(bi);
2416                 name = blk_integrity_name(bi);
2417                 /*
2418                  * Expected values:
2419                  * T10-DIF-TYPE1-CRC
2420                  * T10-DIF-TYPE3-CRC
2421                  * T10-DIF-TYPE1-IP
2422                  * T10-DIF-TYPE3-IP
2423                  */
2424                 if (strncmp(name, "T10-DIF-TYPE",
2425                             sizeof("T10-DIF-TYPE") - 1) == 0) {
2426                         /* also skip "1/3-" at end */
2427                         const int type_off = sizeof("T10-DIF-TYPE.");
2428                         char type_number = name[type_off - 2];
2429
2430                         if (interval != 512 && interval != 4096) {
2431                                 CERROR("%s: unsupported T10PI sector size %u\n",
2432                                        d->od_svname, interval);
2433                         } else if (type_number != '1' && type_number != '3') {
2434                                 CERROR("%s: unsupported T10PI type %s\n",
2435                                        d->od_svname, name);
2436                         } else if (strcmp(name + type_off, "CRC") == 0) {
2437                                 d->od_t10_type = type_number == '1' ?
2438                                         OSD_T10_TYPE1_CRC : OSD_T10_TYPE3_CRC;
2439                                 param->ddp_t10_cksum_type = interval == 512 ?
2440                                         OBD_CKSUM_T10CRC512 :
2441                                         OBD_CKSUM_T10CRC4K;
2442                         } else if (strcmp(name + type_off, "IP") == 0) {
2443                                 d->od_t10_type = type_number == '1' ?
2444                                         OSD_T10_TYPE1_IP : OSD_T10_TYPE3_IP;
2445                                 param->ddp_t10_cksum_type = interval == 512 ?
2446                                         OBD_CKSUM_T10IP512 :
2447                                         OBD_CKSUM_T10IP4K;
2448                         } else {
2449                                 CERROR("%s: unsupported checksum type of "
2450                                        "T10PI type '%s'",
2451                                        d->od_svname, name);
2452                         }
2453
2454                 } else {
2455                         CERROR("%s: unsupported T10PI type '%s'",
2456                                d->od_svname, name);
2457                 }
2458         }
2459 }
2460
2461 static struct super_block *osd_mnt_sb_get(const struct dt_device *d)
2462 {
2463         return osd_sb(osd_dt_dev(d));
2464 }
2465
2466 /*
2467  * Concurrency: shouldn't matter.
2468  */
2469 static int osd_sync(const struct lu_env *env, struct dt_device *d)
2470 {
2471         int rc;
2472         struct super_block *s = osd_sb(osd_dt_dev(d));
2473         ENTRY;
2474
2475         down_read(&s->s_umount);
2476         rc = s->s_op->sync_fs(s, 1);
2477         up_read(&s->s_umount);
2478
2479         CDEBUG(D_CACHE, "%s: synced OSD: rc = %d\n", osd_dt_dev(d)->od_svname,
2480                rc);
2481
2482         return rc;
2483 }
2484
2485 /**
2486  * Start commit for OSD device.
2487  *
2488  * An implementation of dt_commit_async method for OSD device.
2489  * Asychronously starts underlayng fs sync and thereby a transaction
2490  * commit.
2491  *
2492  * \param env environment
2493  * \param d dt device
2494  *
2495  * \see dt_device_operations
2496  */
2497 static int osd_commit_async(const struct lu_env *env,
2498                             struct dt_device *d)
2499 {
2500         struct super_block *s = osd_sb(osd_dt_dev(d));
2501         int rc;
2502
2503         ENTRY;
2504
2505         CDEBUG(D_HA, "%s: async commit OSD\n", osd_dt_dev(d)->od_svname);
2506         down_read(&s->s_umount);
2507         rc = s->s_op->sync_fs(s, 0);
2508         up_read(&s->s_umount);
2509
2510         RETURN(rc);
2511 }
2512
2513 /* Our own copy of the set readonly functions if present, or NU if not. */
2514 static int (*priv_dev_set_rdonly)(struct block_device *bdev);
2515 static int (*priv_dev_check_rdonly)(struct block_device *bdev);
2516 /* static int (*priv_dev_clear_rdonly)(struct block_device *bdev); */
2517
2518 /*
2519  * Concurrency: shouldn't matter.
2520  */
2521 static int osd_ro(const struct lu_env *env, struct dt_device *d)
2522 {
2523         struct super_block *sb = osd_sb(osd_dt_dev(d));
2524         struct block_device *dev = sb->s_bdev;
2525         int rc = -EOPNOTSUPP;
2526
2527         ENTRY;
2528
2529         if (priv_dev_set_rdonly) {
2530                 struct block_device *jdev = LDISKFS_SB(sb)->journal_bdev;
2531
2532                 rc = 0;
2533                 CERROR("*** setting %s read-only ***\n",
2534                        osd_dt_dev(d)->od_svname);
2535
2536                 if (sb->s_op->freeze_fs) {
2537                         rc = sb->s_op->freeze_fs(sb);
2538                         if (rc)
2539                                 goto out;
2540                 }
2541
2542                 if (jdev && (jdev != dev)) {
2543                         CDEBUG(D_IOCTL | D_HA, "set journal dev %lx rdonly\n",
2544                                (long)jdev);
2545                         priv_dev_set_rdonly(jdev);
2546                 }
2547                 CDEBUG(D_IOCTL | D_HA, "set dev %lx rdonly\n", (long)dev);
2548                 priv_dev_set_rdonly(dev);
2549
2550                 if (sb->s_op->unfreeze_fs)
2551                         sb->s_op->unfreeze_fs(sb);
2552         }
2553
2554 out:
2555         if (rc)
2556                 CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
2557                        osd_dt_dev(d)->od_svname, (long)dev, rc);
2558
2559         RETURN(rc);
2560 }
2561
2562 /**
2563  * Note: we do not count into QUOTA here.
2564  * If we mount with --data_journal we may need more.
2565  */
2566 const int osd_dto_credits_noquota[DTO_NR] = {
2567         /**
2568          * Insert.
2569          * INDEX_EXTRA_TRANS_BLOCKS(8) +
2570          * SINGLEDATA_TRANS_BLOCKS(8)
2571          * XXX Note: maybe iam need more, since iam have more level than
2572          *           EXT3 htree.
2573          */
2574         [DTO_INDEX_INSERT]  = 16,
2575         /**
2576          * Delete
2577          * just modify a single entry, probably merge few within a block
2578          */
2579         [DTO_INDEX_DELETE]  = 1,
2580         /**
2581          * Used for OI scrub
2582          */
2583         [DTO_INDEX_UPDATE]  = 16,
2584         /**
2585          * 4(inode, inode bits, groups, GDT)
2586          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
2587          */
2588         [DTO_OBJECT_CREATE] = 4,
2589         /**
2590          * 4(inode, inode bits, groups, GDT)
2591          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
2592          */
2593         [DTO_OBJECT_DELETE] = 4,
2594         /**
2595          * Attr set credits (inode)
2596          */
2597         [DTO_ATTR_SET_BASE] = 1,
2598         /**
2599          * Xattr set. The same as xattr of EXT3.
2600          * DATA_TRANS_BLOCKS(14)
2601          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
2602          * are also counted in. Do not know why?
2603          */
2604         [DTO_XATTR_SET]     = 14,
2605         /**
2606          * credits for inode change during write.
2607          */
2608         [DTO_WRITE_BASE]    = 3,
2609         /**
2610          * credits for single block write.
2611          */
2612         [DTO_WRITE_BLOCK]   = 14,
2613         /**
2614          * Attr set credits for chown.
2615          * This is extra credits for setattr, and it is null without quota
2616          */
2617         [DTO_ATTR_SET_CHOWN] = 0
2618 };
2619
2620 static const struct dt_device_operations osd_dt_ops = {
2621         .dt_root_get       = osd_root_get,
2622         .dt_statfs         = osd_statfs,
2623         .dt_trans_create   = osd_trans_create,
2624         .dt_trans_start    = osd_trans_start,
2625         .dt_trans_stop     = osd_trans_stop,
2626         .dt_trans_cb_add   = osd_trans_cb_add,
2627         .dt_conf_get       = osd_conf_get,
2628         .dt_mnt_sb_get     = osd_mnt_sb_get,
2629         .dt_sync           = osd_sync,
2630         .dt_ro             = osd_ro,
2631         .dt_commit_async   = osd_commit_async,
2632 };
2633
2634 static void osd_read_lock(const struct lu_env *env, struct dt_object *dt,
2635                           unsigned int role)
2636 {
2637         struct osd_object *obj = osd_dt_obj(dt);
2638         struct osd_thread_info *oti = osd_oti_get(env);
2639
2640         LINVRNT(osd_invariant(obj));
2641
2642         LASSERT(obj->oo_owner != env);
2643         down_read_nested(&obj->oo_sem, role);
2644
2645         LASSERT(obj->oo_owner == NULL);
2646         oti->oti_r_locks++;
2647 }
2648
2649 static void osd_write_lock(const struct lu_env *env, struct dt_object *dt,
2650                            unsigned int role)
2651 {
2652         struct osd_object *obj = osd_dt_obj(dt);
2653         struct osd_thread_info *oti = osd_oti_get(env);
2654
2655         LINVRNT(osd_invariant(obj));
2656
2657         LASSERT(obj->oo_owner != env);
2658         down_write_nested(&obj->oo_sem, role);
2659
2660         LASSERT(obj->oo_owner == NULL);
2661         obj->oo_owner = env;
2662         oti->oti_w_locks++;
2663 }
2664
2665 static void osd_read_unlock(const struct lu_env *env, struct dt_object *dt)
2666 {
2667         struct osd_object *obj = osd_dt_obj(dt);
2668         struct osd_thread_info *oti = osd_oti_get(env);
2669
2670         LINVRNT(osd_invariant(obj));
2671
2672         LASSERT(oti->oti_r_locks > 0);
2673         oti->oti_r_locks--;
2674         up_read(&obj->oo_sem);
2675 }
2676
2677 static void osd_write_unlock(const struct lu_env *env, struct dt_object *dt)
2678 {
2679         struct osd_object *obj = osd_dt_obj(dt);
2680         struct osd_thread_info *oti = osd_oti_get(env);
2681
2682         LINVRNT(osd_invariant(obj));
2683
2684         LASSERT(obj->oo_owner == env);
2685         LASSERT(oti->oti_w_locks > 0);
2686         oti->oti_w_locks--;
2687         obj->oo_owner = NULL;
2688         up_write(&obj->oo_sem);
2689 }
2690
2691 static int osd_write_locked(const struct lu_env *env, struct dt_object *dt)
2692 {
2693         struct osd_object *obj = osd_dt_obj(dt);
2694
2695         LINVRNT(osd_invariant(obj));
2696
2697         return obj->oo_owner == env;
2698 }
2699
2700 #ifdef HAVE_INODE_TIMESPEC64
2701 static struct timespec64 osd_inode_time(const struct lu_env *env,
2702                                        struct inode *inode, __u64 seconds)
2703 #else
2704 static struct timespec osd_inode_time(const struct lu_env *env,
2705                                        struct inode *inode, __u64 seconds)
2706 #endif
2707 {
2708         struct osd_thread_info *oti = osd_oti_get(env);
2709         struct timespec *t = &oti->oti_time;
2710
2711         t->tv_sec = seconds;
2712         t->tv_nsec = 0;
2713         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
2714 #ifdef HAVE_INODE_TIMESPEC64
2715         return timespec_to_timespec64(*t);
2716 #else
2717         return *t;
2718 #endif
2719 }
2720
2721 static void osd_inode_getattr(const struct lu_env *env,
2722                               struct inode *inode, struct lu_attr *attr)
2723 {
2724         attr->la_valid  |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
2725                            LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
2726                            LA_PROJID | LA_FLAGS | LA_NLINK | LA_RDEV |
2727                            LA_BLKSIZE | LA_TYPE;
2728
2729         attr->la_atime = inode->i_atime.tv_sec;
2730         attr->la_mtime = inode->i_mtime.tv_sec;
2731         attr->la_ctime = inode->i_ctime.tv_sec;
2732         attr->la_mode    = inode->i_mode;
2733         attr->la_size    = i_size_read(inode);
2734         attr->la_blocks  = inode->i_blocks;
2735         attr->la_uid     = i_uid_read(inode);
2736         attr->la_gid     = i_gid_read(inode);
2737         attr->la_projid  = i_projid_read(inode);
2738         attr->la_flags   = ll_inode_to_ext_flags(inode->i_flags);
2739         attr->la_nlink   = inode->i_nlink;
2740         attr->la_rdev    = inode->i_rdev;
2741         attr->la_blksize = 1 << inode->i_blkbits;
2742         attr->la_blkbits = inode->i_blkbits;
2743         /*
2744          * Ext4 did not transfer inherit flags from raw inode
2745          * to inode flags, and ext4 internally test raw inode
2746          * @i_flags directly. Instead of patching ext4, we do it here.
2747          */
2748         if (LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL)
2749                 attr->la_flags |= LUSTRE_PROJINHERIT_FL;
2750 }
2751
2752 static int osd_attr_get(const struct lu_env *env, struct dt_object *dt,
2753                         struct lu_attr *attr)
2754 {
2755         struct osd_object *obj = osd_dt_obj(dt);
2756
2757         if (unlikely(!dt_object_exists(dt)))
2758                 return -ENOENT;
2759         if (unlikely(obj->oo_destroyed))
2760                 return -ENOENT;
2761
2762         LASSERT(!dt_object_remote(dt));
2763         LINVRNT(osd_invariant(obj));
2764
2765         spin_lock(&obj->oo_guard);
2766         osd_inode_getattr(env, obj->oo_inode, attr);
2767         if (obj->oo_lma_flags & LUSTRE_ORPHAN_FL) {
2768                 attr->la_valid |= LA_FLAGS;
2769                 attr->la_flags |= LUSTRE_ORPHAN_FL;
2770         }
2771         spin_unlock(&obj->oo_guard);
2772
2773         return 0;
2774 }
2775
2776 static int osd_declare_attr_qid(const struct lu_env *env,
2777                                 struct osd_object *obj,
2778                                 struct osd_thandle *oh, long long bspace,
2779                                 qid_t old_id, qid_t new_id, bool enforce,
2780                                 unsigned int type, bool ignore_edquot)
2781 {
2782         int rc;
2783         struct osd_thread_info *info = osd_oti_get(env);
2784         struct lquota_id_info  *qi = &info->oti_qi;
2785
2786         qi->lqi_type = type;
2787         /* inode accounting */
2788         qi->lqi_is_blk = false;
2789
2790         /* one more inode for the new id ... */
2791         qi->lqi_id.qid_uid = new_id;
2792         qi->lqi_space      = 1;
2793         /* Reserve credits for the new id */
2794         rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
2795         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2796                 rc = 0;
2797         if (rc)
2798                 RETURN(rc);
2799
2800         /* and one less inode for the current id */
2801         qi->lqi_id.qid_uid = old_id;
2802         qi->lqi_space = -1;
2803         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2804         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2805                 rc = 0;
2806         if (rc)
2807                 RETURN(rc);
2808
2809         /* block accounting */
2810         qi->lqi_is_blk = true;
2811
2812         /* more blocks for the new id ... */
2813         qi->lqi_id.qid_uid = new_id;
2814         qi->lqi_space      = bspace;
2815         /*
2816          * Credits for the new uid has been reserved, re-use "obj"
2817          * to save credit reservation.
2818          */
2819         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2820         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2821                 rc = 0;
2822         if (rc)
2823                 RETURN(rc);
2824
2825         /* and finally less blocks for the current uid */
2826         qi->lqi_id.qid_uid = old_id;
2827         qi->lqi_space      = -bspace;
2828         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2829         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2830                 rc = 0;
2831
2832         RETURN(rc);
2833 }
2834
2835 static int osd_declare_attr_set(const struct lu_env *env,
2836                                 struct dt_object *dt,
2837                                 const struct lu_attr *attr,
2838                                 struct thandle *handle)
2839 {
2840         struct osd_thandle *oh;
2841         struct osd_object *obj;
2842         qid_t uid;
2843         qid_t gid;
2844         long long bspace;
2845         int rc = 0;
2846         bool enforce;
2847
2848         ENTRY;
2849
2850         LASSERT(dt != NULL);
2851         LASSERT(handle != NULL);
2852
2853         obj = osd_dt_obj(dt);
2854         LASSERT(osd_invariant(obj));
2855
2856         oh = container_of0(handle, struct osd_thandle, ot_super);
2857         LASSERT(oh->ot_handle == NULL);
2858
2859         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
2860                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2861
2862         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2863                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2864
2865         if (attr == NULL || obj->oo_inode == NULL)
2866                 RETURN(rc);
2867
2868         bspace   = obj->oo_inode->i_blocks << 9;
2869         bspace   = toqb(bspace);
2870
2871         /*
2872          * Changing ownership is always preformed by super user, it should not
2873          * fail with EDQUOT unless required explicitly.
2874          *
2875          * We still need to call the osd_declare_qid() to calculate the journal
2876          * credits for updating quota accounting files and to trigger quota
2877          * space adjustment once the operation is completed.
2878          */
2879         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
2880                 bool ignore_edquot = !(attr->la_flags & LUSTRE_SET_SYNC_FL);
2881
2882                 if (!ignore_edquot)
2883                         CDEBUG(D_QUOTA, "%s: enforce quota on UID %u, GID %u"
2884                                "(the quota space is %lld)\n",
2885                                obj->oo_inode->i_sb->s_id, attr->la_uid,
2886                                attr->la_gid, bspace);
2887
2888                 /* USERQUOTA */
2889                 uid = i_uid_read(obj->oo_inode);
2890                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
2891                 rc = osd_declare_attr_qid(env, obj, oh, bspace, uid,
2892                                           attr->la_uid, enforce, USRQUOTA,
2893                                           true);
2894                 if (rc)
2895                         RETURN(rc);
2896
2897                 gid = i_gid_read(obj->oo_inode);
2898                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
2899                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2900                                           i_gid_read(obj->oo_inode),
2901                                           attr->la_gid, enforce, GRPQUOTA,
2902                                           ignore_edquot);
2903                 if (rc)
2904                         RETURN(rc);
2905
2906         }
2907 #ifdef HAVE_PROJECT_QUOTA
2908         if (attr->la_valid & LA_PROJID) {
2909                 __u32 projid = i_projid_read(obj->oo_inode);
2910
2911                 enforce = (attr->la_valid & LA_PROJID) &&
2912                                         (attr->la_projid != projid);
2913                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2914                                           (qid_t)projid, (qid_t)attr->la_projid,
2915                                           enforce, PRJQUOTA, true);
2916                 if (rc)
2917                         RETURN(rc);
2918         }
2919 #endif
2920         RETURN(rc);
2921 }
2922
2923 static int osd_inode_setattr(const struct lu_env *env,
2924                              struct inode *inode, const struct lu_attr *attr)
2925 {
2926         __u64 bits = attr->la_valid;
2927
2928         /* Only allow set size for regular file */
2929         if (!S_ISREG(inode->i_mode))
2930                 bits &= ~(LA_SIZE | LA_BLOCKS);
2931
2932         if (bits == 0)
2933                 return 0;
2934
2935         if (bits & LA_ATIME)
2936                 inode->i_atime  = osd_inode_time(env, inode, attr->la_atime);
2937         if (bits & LA_CTIME)
2938                 inode->i_ctime  = osd_inode_time(env, inode, attr->la_ctime);
2939         if (bits & LA_MTIME)
2940                 inode->i_mtime  = osd_inode_time(env, inode, attr->la_mtime);
2941         if (bits & LA_SIZE) {
2942                 spin_lock(&inode->i_lock);
2943                 LDISKFS_I(inode)->i_disksize = attr->la_size;
2944                 i_size_write(inode, attr->la_size);
2945                 spin_unlock(&inode->i_lock);
2946         }
2947
2948         /*
2949          * OSD should not change "i_blocks" which is used by quota.
2950          * "i_blocks" should be changed by ldiskfs only.
2951          */
2952         if (bits & LA_MODE)
2953                 inode->i_mode = (inode->i_mode & S_IFMT) |
2954                                 (attr->la_mode & ~S_IFMT);
2955         if (bits & LA_UID)
2956                 i_uid_write(inode, attr->la_uid);
2957         if (bits & LA_GID)
2958                 i_gid_write(inode, attr->la_gid);
2959         if (bits & LA_PROJID)
2960                 i_projid_write(inode, attr->la_projid);
2961         if (bits & LA_NLINK)
2962                 set_nlink(inode, attr->la_nlink);
2963         if (bits & LA_RDEV)
2964                 inode->i_rdev = attr->la_rdev;
2965
2966         if (bits & LA_FLAGS) {
2967                 /* always keep S_NOCMTIME */
2968                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
2969                                  S_NOCMTIME;
2970                 /*
2971                  * Ext4 did not transfer inherit flags from
2972                  * @inode->i_flags to raw inode i_flags when writing
2973                  * flags, we do it explictly here.
2974                  */
2975                 if (attr->la_flags & LUSTRE_PROJINHERIT_FL)
2976                         LDISKFS_I(inode)->i_flags |= LUSTRE_PROJINHERIT_FL;
2977                 else
2978                         LDISKFS_I(inode)->i_flags &= ~LUSTRE_PROJINHERIT_FL;
2979         }
2980         return 0;
2981 }
2982
2983 #ifdef HAVE_PROJECT_QUOTA
2984 static int osd_transfer_project(struct inode *inode, __u32 projid,
2985                                 struct thandle *handle)
2986 {
2987         struct super_block *sb = inode->i_sb;
2988         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
2989         int err;
2990         kprojid_t kprojid;
2991         struct ldiskfs_iloc iloc;
2992         struct ldiskfs_inode *raw_inode;
2993         struct dquot *transfer_to[LDISKFS_MAXQUOTAS] = { };
2994
2995         if (!ldiskfs_has_feature_project(sb)) {
2996                 LASSERT(__kprojid_val(LDISKFS_I(inode)->i_projid)
2997                         == LDISKFS_DEF_PROJID);
2998                 if (projid != LDISKFS_DEF_PROJID)
2999                         return -EOPNOTSUPP;
3000                 else
3001                         return 0;
3002         }
3003
3004         if (LDISKFS_INODE_SIZE(sb) <= LDISKFS_GOOD_OLD_INODE_SIZE)
3005                 return -EOPNOTSUPP;
3006
3007         kprojid = make_kprojid(&init_user_ns, (projid_t)projid);
3008         if (projid_eq(kprojid, LDISKFS_I(inode)->i_projid))
3009                 return 0;
3010
3011         err = ldiskfs_get_inode_loc(inode, &iloc);
3012         if (err)
3013                 return err;
3014
3015         raw_inode = ldiskfs_raw_inode(&iloc);
3016         if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3017                 struct osd_thandle *oh =
3018                                 container_of0(handle, struct osd_thandle,
3019                                               ot_super);
3020                 /**
3021                  * try to expand inode size automatically.
3022                  */
3023                 ldiskfs_mark_inode_dirty(oh->ot_handle, inode);
3024                 if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3025                         err = -EOVERFLOW;
3026                         brelse(iloc.bh);
3027                         return err;
3028                 }
3029         }
3030         brelse(iloc.bh);
3031
3032         dquot_initialize(inode);
3033         transfer_to[PRJQUOTA] = dqget(sb, make_kqid_projid(kprojid));
3034         if (transfer_to[PRJQUOTA]) {
3035                 err = __dquot_transfer(inode, transfer_to);
3036                 dqput(transfer_to[PRJQUOTA]);
3037                 if (err)
3038                         return err;
3039         }
3040
3041         return err;
3042 }
3043 #endif
3044
3045 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr,
3046                               struct thandle *handle)
3047 {
3048         int rc;
3049
3050         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
3051             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
3052                 struct iattr iattr;
3053
3054                 ll_vfs_dq_init(inode);
3055                 iattr.ia_valid = 0;
3056                 if (attr->la_valid & LA_UID)
3057                         iattr.ia_valid |= ATTR_UID;
3058                 if (attr->la_valid & LA_GID)
3059                         iattr.ia_valid |= ATTR_GID;
3060                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3061                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3062
3063                 rc = ll_vfs_dq_transfer(inode, &iattr);
3064                 if (rc) {
3065                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
3066                                "enforcement enabled on the ldiskfs "
3067                                "filesystem?\n", inode->i_sb->s_id, rc);
3068                         return rc;
3069                 }
3070         }
3071
3072         /* Handle project id transfer here properly */
3073         if (attr->la_valid & LA_PROJID &&
3074             attr->la_projid != i_projid_read(inode)) {
3075 #ifdef HAVE_PROJECT_QUOTA
3076                 rc = osd_transfer_project(inode, attr->la_projid, handle);
3077 #else
3078                 rc = -ENOTSUPP;
3079 #endif
3080                 if (rc) {
3081                         CERROR("%s: quota transfer failed: rc = %d. Is project "
3082                                "enforcement enabled on the ldiskfs "
3083                                "filesystem?\n", inode->i_sb->s_id, rc);
3084                         return rc;
3085                 }
3086         }
3087         return 0;
3088 }
3089
3090 static int osd_attr_set(const struct lu_env *env,
3091                         struct dt_object *dt,
3092                         const struct lu_attr *attr,
3093                         struct thandle *handle)
3094 {
3095         struct osd_object *obj = osd_dt_obj(dt);
3096         struct inode *inode;
3097         int rc;
3098
3099         if (!dt_object_exists(dt))
3100                 return -ENOENT;
3101
3102         LASSERT(handle != NULL);
3103         LASSERT(!dt_object_remote(dt));
3104         LASSERT(osd_invariant(obj));
3105
3106         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
3107
3108         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING) &&
3109             !osd_obj2dev(obj)->od_is_ost) {
3110                 struct osd_thread_info *oti = osd_oti_get(env);
3111                 const struct lu_fid *fid0 = lu_object_fid(&dt->do_lu);
3112                 struct lu_fid *fid1 = &oti->oti_fid;
3113                 struct osd_inode_id *id = &oti->oti_id;
3114                 struct iam_path_descr *ipd;
3115                 struct iam_container *bag;
3116                 struct osd_thandle *oh;
3117                 int rc;
3118
3119                 fid_cpu_to_be(fid1, fid0);
3120                 memset(id, 1, sizeof(*id));
3121                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
3122                                   fid0)->oi_dir.od_container;
3123                 ipd = osd_idx_ipd_get(env, bag);
3124                 if (unlikely(ipd == NULL))
3125                         RETURN(-ENOMEM);
3126
3127                 oh = container_of0(handle, struct osd_thandle, ot_super);
3128                 rc = iam_update(oh->ot_handle, bag,
3129                                 (const struct iam_key *)fid1,
3130                                 (const struct iam_rec *)id, ipd);
3131                 osd_ipd_put(env, bag, ipd);
3132                 return(rc > 0 ? 0 : rc);
3133         }
3134
3135         inode = obj->oo_inode;
3136
3137         rc = osd_quota_transfer(inode, attr, handle);
3138         if (rc)
3139                 return rc;
3140
3141         spin_lock(&obj->oo_guard);
3142         rc = osd_inode_setattr(env, inode, attr);
3143         spin_unlock(&obj->oo_guard);
3144         if (rc != 0)
3145                 GOTO(out, rc);
3146
3147         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3148
3149         if (!(attr->la_valid & LA_FLAGS))
3150                 GOTO(out, rc);
3151
3152         /* Let's check if there are extra flags need to be set into LMA */
3153         if (attr->la_flags & LUSTRE_LMA_FL_MASKS) {
3154                 struct osd_thread_info *info = osd_oti_get(env);
3155                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
3156
3157                 LASSERT(!obj->oo_pfid_in_lma);
3158
3159                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
3160                                  &info->oti_ost_attrs);
3161                 if (rc)
3162                         GOTO(out, rc);
3163
3164                 lma->lma_incompat |=
3165                         lustre_to_lma_flags(attr->la_flags);
3166                 lustre_lma_swab(lma);
3167                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA,
3168                                      lma, sizeof(*lma), XATTR_REPLACE);
3169                 if (rc != 0) {
3170                         struct osd_device *osd = osd_obj2dev(obj);
3171
3172                         CWARN("%s: set "DFID" lma flags %u failed: rc = %d\n",
3173                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
3174                               lma->lma_incompat, rc);
3175                 } else {
3176                         obj->oo_lma_flags =
3177                                 attr->la_flags & LUSTRE_LMA_FL_MASKS;
3178                 }
3179                 osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
3180         }
3181 out:
3182         osd_trans_exec_check(env, handle, OSD_OT_ATTR_SET);
3183
3184         return rc;
3185 }
3186
3187 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
3188                                            struct osd_object *obj,
3189                                            const char *name, const int namelen)
3190 {
3191         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
3192 }
3193
3194 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
3195                       umode_t mode, struct dt_allocation_hint *hint,
3196                       struct thandle *th, struct lu_attr *attr)
3197 {
3198         int result;
3199         struct osd_device *osd = osd_obj2dev(obj);
3200         struct osd_thandle *oth;
3201         struct dt_object *parent = NULL;
3202         struct inode *inode;
3203         uid_t owner[2] = {0, 0};
3204
3205         if (attr->la_valid & LA_UID)
3206                 owner[0] = attr->la_uid;
3207         if (attr->la_valid & LA_GID)
3208                 owner[1] = attr->la_gid;
3209
3210         LINVRNT(osd_invariant(obj));
3211         LASSERT(obj->oo_inode == NULL);
3212         LASSERT(obj->oo_hl_head == NULL);
3213
3214         if (S_ISDIR(mode) && ldiskfs_pdo) {
3215                 obj->oo_hl_head =
3216                         ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
3217                 if (obj->oo_hl_head == NULL)
3218                         return -ENOMEM;
3219         }
3220
3221         oth = container_of(th, struct osd_thandle, ot_super);
3222         LASSERT(oth->ot_handle->h_transaction != NULL);
3223
3224         if (hint != NULL && hint->dah_parent != NULL &&
3225             !dt_object_remote(hint->dah_parent))
3226                 parent = hint->dah_parent;
3227
3228         inode = ldiskfs_create_inode(oth->ot_handle,
3229                                      parent ? osd_dt_obj(parent)->oo_inode :
3230                                               osd_sb(osd)->s_root->d_inode,
3231                                      mode, owner);
3232         if (!IS_ERR(inode)) {
3233                 /* Do not update file c/mtime in ldiskfs. */
3234                 inode->i_flags |= S_NOCMTIME;
3235
3236                 /*
3237                  * For new created object, it must be consistent,
3238                  * and it is unnecessary to scrub against it.
3239                  */
3240                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
3241
3242                 obj->oo_inode = inode;
3243                 result = 0;
3244         } else {
3245                 if (obj->oo_hl_head != NULL) {
3246                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
3247                         obj->oo_hl_head = NULL;
3248                 }
3249                 result = PTR_ERR(inode);
3250         }
3251         LINVRNT(osd_invariant(obj));
3252         return result;
3253 }
3254
3255 enum {
3256         OSD_NAME_LEN = 255
3257 };
3258
3259 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
3260                      struct lu_attr *attr,
3261                      struct dt_allocation_hint *hint,
3262                      struct dt_object_format *dof,
3263                      struct thandle *th)
3264 {
3265         int result;
3266         struct osd_thandle *oth;
3267         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX | S_ISGID));
3268
3269         LASSERT(S_ISDIR(attr->la_mode));
3270
3271         oth = container_of(th, struct osd_thandle, ot_super);
3272         LASSERT(oth->ot_handle->h_transaction != NULL);
3273         result = osd_mkfile(info, obj, mode, hint, th, attr);
3274
3275         return result;
3276 }
3277
3278 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
3279                         struct lu_attr *attr,
3280                         struct dt_allocation_hint *hint,
3281                         struct dt_object_format *dof,
3282                         struct thandle *th)
3283 {
3284         int result;
3285         struct osd_thandle *oth;
3286         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
3287
3288         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
3289
3290         LASSERT(S_ISREG(attr->la_mode));
3291
3292         oth = container_of(th, struct osd_thandle, ot_super);
3293         LASSERT(oth->ot_handle->h_transaction != NULL);
3294
3295         result = osd_mkfile(info, obj, mode, hint, th, attr);
3296         if (result == 0) {
3297                 LASSERT(obj->oo_inode != NULL);
3298                 if (feat->dif_flags & DT_IND_VARKEY)
3299                         result = iam_lvar_create(obj->oo_inode,
3300                                                  feat->dif_keysize_max,
3301                                                  feat->dif_ptrsize,
3302                                                  feat->dif_recsize_max,
3303                                                  oth->ot_handle);
3304                 else
3305                         result = iam_lfix_create(obj->oo_inode,
3306                                                  feat->dif_keysize_max,
3307                                                  feat->dif_ptrsize,
3308                                                  feat->dif_recsize_max,
3309                                                  oth->ot_handle);
3310         }
3311         return result;
3312 }
3313
3314 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
3315                      struct lu_attr *attr,
3316                      struct dt_allocation_hint *hint,
3317                      struct dt_object_format *dof,
3318                      struct thandle *th)
3319 {
3320         LASSERT(S_ISREG(attr->la_mode));
3321         return osd_mkfile(info, obj, (attr->la_mode &
3322                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3323                           attr);
3324 }
3325
3326 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
3327                      struct lu_attr *attr,
3328                      struct dt_allocation_hint *hint,
3329                      struct dt_object_format *dof,
3330                      struct thandle *th)
3331 {
3332         LASSERT(S_ISLNK(attr->la_mode));
3333         return osd_mkfile(info, obj, (attr->la_mode &
3334                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3335                           attr);
3336 }
3337
3338 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
3339                      struct lu_attr *attr,
3340                      struct dt_allocation_hint *hint,
3341                      struct dt_object_format *dof,
3342                      struct thandle *th)
3343 {
3344         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
3345         int result;
3346
3347         LINVRNT(osd_invariant(obj));
3348         LASSERT(obj->oo_inode == NULL);
3349         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
3350                 S_ISFIFO(mode) || S_ISSOCK(mode));
3351
3352         result = osd_mkfile(info, obj, mode, hint, th, attr);
3353         if (result == 0) {
3354                 LASSERT(obj->oo_inode != NULL);
3355                 /*
3356                  * This inode should be marked dirty for i_rdev.  Currently
3357                  * that is done in the osd_attr_init().
3358                  */
3359                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
3360                                    attr->la_rdev);
3361         }
3362         LINVRNT(osd_invariant(obj));
3363         return result;
3364 }
3365
3366 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
3367                               struct lu_attr *,
3368                               struct dt_allocation_hint *hint,
3369                               struct dt_object_format *dof,
3370                               struct thandle *);
3371
3372 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
3373 {
3374         osd_obj_type_f result;
3375
3376         switch (type) {
3377         case DFT_DIR:
3378                 result = osd_mkdir;
3379                 break;
3380         case DFT_REGULAR:
3381                 result = osd_mkreg;
3382                 break;
3383         case DFT_SYM:
3384                 result = osd_mksym;
3385                 break;
3386         case DFT_NODE:
3387                 result = osd_mknod;
3388                 break;
3389         case DFT_INDEX:
3390                 result = osd_mk_index;
3391                 break;
3392
3393         default:
3394                 LBUG();
3395                 break;
3396         }
3397         return result;
3398 }
3399
3400
3401 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
3402                         struct dt_object *parent, struct dt_object *child,
3403                         umode_t child_mode)
3404 {
3405         LASSERT(ah);
3406
3407         ah->dah_parent = parent;
3408         ah->dah_mode = child_mode;
3409
3410         if (parent != NULL && !dt_object_remote(parent)) {
3411                 /* will help to find FID->ino at dt_insert("..") */
3412                 struct osd_object *pobj = osd_dt_obj(parent);
3413
3414                 osd_idc_find_and_init(env, osd_obj2dev(pobj), pobj);
3415         }
3416 }
3417
3418 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
3419                           struct lu_attr *attr, struct dt_object_format *dof,
3420                           struct thandle *handle)
3421 {
3422         struct inode *inode = obj->oo_inode;
3423         __u64 valid = attr->la_valid;
3424         int result;
3425
3426         attr->la_valid &= ~(LA_TYPE | LA_MODE);
3427
3428         if (dof->dof_type != DFT_NODE)
3429                 attr->la_valid &= ~LA_RDEV;
3430         if ((valid & LA_ATIME) && (attr->la_atime == inode->i_atime.tv_sec))
3431                 attr->la_valid &= ~LA_ATIME;
3432         if ((valid & LA_CTIME) && (attr->la_ctime == inode->i_ctime.tv_sec))
3433                 attr->la_valid &= ~LA_CTIME;
3434         if ((valid & LA_MTIME) && (attr->la_mtime == inode->i_mtime.tv_sec))
3435                 attr->la_valid &= ~LA_MTIME;
3436
3437         result = osd_quota_transfer(inode, attr, handle);
3438         if (result)
3439                 return;
3440
3441         if (attr->la_valid != 0) {
3442                 result = osd_inode_setattr(info->oti_env, inode, attr);
3443                 /*
3444                  * The osd_inode_setattr() should always succeed here.  The
3445                  * only error that could be returned is EDQUOT when we are
3446                  * trying to change the UID or GID of the inode. However, this
3447                  * should not happen since quota enforcement is no longer
3448                  * enabled on ldiskfs (lquota takes care of it).
3449                  */
3450                 LASSERTF(result == 0, "%d\n", result);
3451                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3452         }
3453
3454         attr->la_valid = valid;
3455 }
3456
3457 /**
3458  * Helper function for osd_create()
3459  *
3460  * \retval 0, on success
3461  */
3462 static int __osd_create(struct osd_thread_info *info, struct osd_object *obj,
3463                         struct lu_attr *attr, struct dt_allocation_hint *hint,
3464                         struct dt_object_format *dof, struct thandle *th)
3465 {
3466         int result;
3467         __u32 umask;
3468
3469         osd_trans_exec_op(info->oti_env, th, OSD_OT_CREATE);
3470
3471         /* we drop umask so that permissions we pass are not affected */
3472         umask = current->fs->umask;
3473         current->fs->umask = 0;
3474
3475         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
3476                                                   th);
3477         if (likely(obj->oo_inode != NULL)) {
3478                 LASSERT(obj->oo_inode->i_state & I_NEW);
3479
3480                 /*
3481                  * Unlock the inode before attr initialization to avoid
3482                  * unnecessary dqget operations. LU-6378
3483                  */
3484                 unlock_new_inode(obj->oo_inode);
3485         }
3486
3487         if (likely(result == 0)) {
3488                 osd_attr_init(info, obj, attr, dof, th);
3489                 osd_object_init0(obj);
3490         }
3491
3492         /* restore previous umask value */
3493         current->fs->umask = umask;
3494
3495         osd_trans_exec_check(info->oti_env, th, OSD_OT_CREATE);
3496
3497         return result;
3498 }
3499
3500 /**
3501  * Helper function for osd_create()
3502  *
3503  * \retval 0, on success
3504  */
3505 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
3506                            const struct lu_fid *fid, struct thandle *th)
3507 {
3508         struct osd_thread_info *info = osd_oti_get(env);
3509         struct osd_inode_id    *id   = &info->oti_id;
3510         struct osd_device      *osd  = osd_obj2dev(obj);
3511         struct osd_thandle     *oh;
3512         int rc;
3513
3514         LASSERT(obj->oo_inode != NULL);
3515
3516         oh = container_of0(th, struct osd_thandle, ot_super);
3517         LASSERT(oh->ot_handle);
3518         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3519
3520         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
3521         rc = osd_oi_insert(info, osd, fid, id, oh->ot_handle,
3522                            OI_CHECK_FLD, NULL);
3523         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP) && osd->od_is_ost) {
3524                 struct lu_fid next_fid = *fid;
3525
3526                 /* insert next object in advance, and map to the same inode */
3527                 next_fid.f_oid++;
3528                 if (next_fid.f_oid != 0) {
3529                         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3530                         osd_oi_insert(info, osd, &next_fid, id, oh->ot_handle,
3531                                       OI_CHECK_FLD, NULL);
3532                         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3533                 }
3534         }
3535
3536         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3537
3538         return rc;
3539 }
3540
3541 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
3542                    u64 seq, struct lu_seq_range *range)
3543 {
3544         struct seq_server_site *ss = osd_seq_site(osd);
3545
3546         if (fid_seq_is_idif(seq)) {
3547                 fld_range_set_ost(range);
3548                 range->lsr_index = idif_ost_idx(seq);
3549                 return 0;
3550         }
3551
3552         if (!fid_seq_in_fldb(seq)) {
3553                 fld_range_set_mdt(range);
3554                 if (ss != NULL)
3555                         /*
3556                          * FIXME: If ss is NULL, it suppose not get lsr_index
3557                          * at all
3558                          */
3559                         range->lsr_index = ss->ss_node_id;
3560                 return 0;
3561         }
3562
3563         LASSERT(ss != NULL);
3564         fld_range_set_any(range);
3565         /* OSD will only do local fld lookup */
3566         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
3567 }
3568
3569 static int osd_declare_create(const struct lu_env *env, struct dt_object *dt,
3570                               struct lu_attr *attr,
3571                               struct dt_allocation_hint *hint,
3572                               struct dt_object_format *dof,
3573                               struct thandle *handle)
3574 {
3575         struct osd_thandle *oh;
3576         int rc;
3577
3578         ENTRY;
3579
3580         LASSERT(handle != NULL);
3581
3582         oh = container_of0(handle, struct osd_thandle, ot_super);
3583         LASSERT(oh->ot_handle == NULL);
3584
3585         /*
3586          * EA object consumes more credits than regular object: osd_mk_index
3587          * vs. osd_mkreg: osd_mk_index will create 2 blocks for root_node and
3588          * leaf_node, could involves the block, block bitmap, groups, GDT
3589          * change for each block, so add 4 * 2 credits in that case.
3590          */
3591         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
3592                              osd_dto_credits_noquota[DTO_OBJECT_CREATE] +
3593                              (dof->dof_type == DFT_INDEX) ? 4 * 2 : 0);
3594         /*
3595          * Reuse idle OI block may cause additional one OI block
3596          * to be changed.
3597          */
3598         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3599                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3600         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP))
3601                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3602                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3603
3604         /* will help to find FID->ino mapping at dt_insert() */
3605         rc = osd_idc_find_and_init(env, osd_obj2dev(osd_dt_obj(dt)),
3606                                    osd_dt_obj(dt));
3607         if (rc != 0)
3608                 RETURN(rc);
3609
3610         if (!attr)
3611                 RETURN(0);
3612
3613         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid,
3614                                    attr->la_projid, 1, oh, osd_dt_obj(dt),
3615                                    NULL, OSD_QID_INODE);
3616         if (rc != 0)
3617                 RETURN(rc);
3618
3619         RETURN(rc);
3620 }
3621
3622 /**
3623  * Called to destroy on-disk representation of the object
3624  *
3625  * Concurrency: must be locked
3626  */
3627 static int osd_declare_destroy(const struct lu_env *env, struct dt_object *dt,
3628                                struct thandle *th)
3629 {
3630         struct osd_object *obj = osd_dt_obj(dt);
3631         struct inode *inode = obj->oo_inode;
3632         struct osd_thandle *oh;
3633         int rc;
3634
3635         ENTRY;
3636
3637         if (inode == NULL)
3638                 RETURN(-ENOENT);
3639
3640         oh = container_of0(th, struct osd_thandle, ot_super);
3641         LASSERT(oh->ot_handle == NULL);
3642
3643         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
3644                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
3645
3646         /* For removing agent entry */
3647         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu))
3648                 oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
3649
3650         /*
3651          * Recycle idle OI leaf may cause additional three OI blocks
3652          * to be changed.
3653          */
3654         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3655                 osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3656                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
3657         /* one less inode */
3658         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3659                                    i_projid_read(inode), -1, oh, obj, NULL,
3660                                    OSD_QID_INODE);
3661         if (rc)
3662                 RETURN(rc);
3663         /* data to be truncated */
3664         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3665                                    i_projid_read(inode), 0, oh, obj, NULL,
3666                                    OSD_QID_BLK);
3667         if (rc)
3668                 RETURN(rc);
3669
3670         /*
3671          * will help to find FID->ino when this object is being
3672          * added to PENDING
3673          */
3674         rc = osd_idc_find_and_init(env, osd_obj2dev(obj), obj);
3675
3676         RETURN(rc);
3677 }
3678
3679 static int osd_destroy(const struct lu_env *env, struct dt_object *dt,
3680                        struct thandle *th)
3681 {
3682         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3683         struct osd_object *obj = osd_dt_obj(dt);
3684         struct inode *inode = obj->oo_inode;
3685         struct osd_device *osd = osd_obj2dev(obj);
3686         struct osd_thandle *oh;
3687         int result;
3688
3689         ENTRY;
3690
3691         oh = container_of0(th, struct osd_thandle, ot_super);
3692         LASSERT(oh->ot_handle);
3693         LASSERT(inode);
3694         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
3695
3696         if (unlikely(fid_is_acct(fid)))
3697                 RETURN(-EPERM);
3698
3699         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu)) {
3700                 result = osd_delete_from_remote_parent(env, osd, obj, oh, true);
3701                 if (result != 0)
3702                         CERROR("%s: remove agent entry "DFID": rc = %d\n",
3703                                osd_name(osd), PFID(fid), result);
3704         }
3705
3706         if (S_ISDIR(inode->i_mode)) {
3707                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1 ||
3708                         inode->i_nlink == 2);
3709
3710                 spin_lock(&obj->oo_guard);
3711                 clear_nlink(inode);
3712                 spin_unlock(&obj->oo_guard);
3713                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3714         }
3715
3716         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
3717
3718         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
3719
3720         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3721                 result = osd_oi_delete(osd_oti_get(env), osd, fid,
3722                                        oh->ot_handle, OI_CHECK_FLD);
3723
3724         osd_trans_exec_check(env, th, OSD_OT_DESTROY);
3725         /* XXX: add to ext3 orphan list */
3726         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
3727
3728         /* not needed in the cache anymore */
3729         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
3730         obj->oo_destroyed = 1;
3731
3732         RETURN(0);
3733 }
3734
3735 /**
3736  * Put the fid into lustre_mdt_attrs, and then place the structure
3737  * inode's ea. This fid should not be altered during the life time
3738  * of the inode.
3739  *
3740  * \retval +ve, on success
3741  * \retval -ve, on error
3742  *
3743  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
3744  */
3745 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
3746                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
3747 {
3748         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
3749         struct lustre_mdt_attrs *lma = &loa->loa_lma;
3750         int rc;
3751
3752         ENTRY;
3753
3754         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
3755                 RETURN(0);
3756
3757         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_OST_EA_FID_SET))
3758                 rc = -ENOMEM;
3759
3760         lustre_loa_init(loa, fid, compat, incompat);
3761         lustre_loa_swab(loa, false);
3762
3763         /*
3764          * For the OST device with 256 bytes inode size by default,
3765          * the PFID EA will be stored together with LMA EA to avoid
3766          * performance trouble. Otherwise the PFID EA can be stored
3767          * independently. LU-8998
3768          */
3769         if ((compat & LMAC_FID_ON_OST) &&
3770             LDISKFS_INODE_SIZE(inode->i_sb) <= 256)
3771                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3772                                      sizeof(*loa), XATTR_CREATE);
3773         else
3774                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3775                                      sizeof(*lma), XATTR_CREATE);
3776         /*
3777          * LMA may already exist, but we need to check that all the
3778          * desired compat/incompat flags have been added.
3779          */
3780         if (unlikely(rc == -EEXIST)) {
3781                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
3782                                      XATTR_NAME_LMA, (void *)loa, sizeof(*loa));
3783                 if (rc < 0)
3784                         RETURN(rc);
3785
3786                 if (rc < sizeof(*lma))
3787                         RETURN(-EINVAL);
3788
3789                 lustre_loa_swab(loa, true);
3790                 if (lu_fid_eq(fid, &lma->lma_self_fid) &&
3791                     ((compat == 0 && incompat == 0) ||
3792                      (!(~lma->lma_compat & compat) &&
3793                       !(~lma->lma_incompat & incompat))))
3794                         RETURN(0);
3795
3796                 lma->lma_self_fid = *fid;
3797                 lma->lma_compat |= compat;
3798                 lma->lma_incompat |= incompat;
3799                 if (rc == sizeof(*lma)) {
3800                         lustre_lma_swab(lma);
3801                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3802                                              sizeof(*lma), XATTR_REPLACE);
3803                 } else {
3804                         lustre_loa_swab(loa, false);
3805                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3806                                              sizeof(*loa), XATTR_REPLACE);
3807                 }
3808         }
3809
3810         RETURN(rc);
3811 }
3812
3813 /**
3814  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
3815  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
3816  * To have compatilibility with 1.8 ldiskfs driver we need to have
3817  * magic number at start of fid data.
3818  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
3819  * its inmemory API.
3820  */
3821 static void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
3822                                          const struct lu_fid *fid)
3823 {
3824         if (!fid_is_namespace_visible(fid) ||
3825             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
3826                 param->edp_magic = 0;
3827                 return;
3828         }
3829
3830         param->edp_magic = LDISKFS_LUFID_MAGIC;
3831         param->edp_len =  sizeof(struct lu_fid) + 1;
3832         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
3833 }
3834
3835 /**
3836  * Try to read the fid from inode ea into dt_rec.
3837  *
3838  * \param fid object fid.
3839  *
3840  * \retval 0 on success
3841  */
3842 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
3843                           __u32 ino, struct lu_fid *fid,
3844                           struct osd_inode_id *id)
3845 {
3846         struct osd_thread_info *info  = osd_oti_get(env);
3847         struct inode *inode;
3848
3849         ENTRY;
3850
3851         osd_id_gen(id, ino, OSD_OII_NOGEN);
3852         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
3853         if (IS_ERR(inode))
3854                 RETURN(PTR_ERR(inode));
3855
3856         iput(inode);
3857         RETURN(0);
3858 }
3859
3860 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
3861                                         struct inode *dir,
3862                                         struct inode *parent_dir,
3863                                         const struct lu_fid *dot_fid,
3864                                         const struct lu_fid *dot_dot_fid,
3865                                         struct osd_thandle *oth)
3866 {
3867         struct ldiskfs_dentry_param *dot_ldp;
3868         struct ldiskfs_dentry_param *dot_dot_ldp;
3869         __u32 saved_nlink = dir->i_nlink;
3870         int rc;
3871
3872         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
3873         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
3874
3875         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3876         dot_ldp->edp_magic = 0;
3877
3878         rc = ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
3879                                     dir, dot_ldp, dot_dot_ldp);
3880         /*
3881          * The ldiskfs_add_dot_dotdot() may dir->i_nlink as 2, then
3882          * the subseqent ref_add() will increase the dir->i_nlink
3883          * as 3. That is incorrect for new created directory.
3884          *
3885          * It looks like hack, because we want to make the OSD API
3886          * to be order-independent for new created directory object
3887          * between dt_insert(..) and ref_add() operations.
3888          *
3889          * Here, we only restore the in-RAM dir-inode's nlink attr,
3890          * becuase if the nlink attr is not 2, then there will be
3891          * ref_add() called following the dt_insert(..), such call
3892          * will make both the in-RAM and on-disk dir-inode's nlink
3893          * attr to be set as 2. LU-7447
3894          */
3895         set_nlink(dir, saved_nlink);
3896         return rc;
3897 }
3898
3899 /**
3900  * Create an local agent inode for remote entry
3901  */
3902 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
3903                                                   struct osd_device *osd,
3904                                                   struct osd_object *pobj,
3905                                                   const struct lu_fid *fid,
3906                                                   __u32 type,
3907                                                   struct thandle *th)
3908 {
3909         struct osd_thread_info *info = osd_oti_get(env);
3910         struct inode *local;
3911         struct osd_thandle *oh;
3912         uid_t own[2] = {0, 0};
3913         int rc;
3914
3915         ENTRY;
3916
3917         LASSERT(th);
3918         oh = container_of(th, struct osd_thandle, ot_super);
3919         LASSERT(oh->ot_handle->h_transaction != NULL);
3920
3921         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, type, own);
3922         if (IS_ERR(local)) {
3923                 CERROR("%s: create local error %d\n", osd_name(osd),
3924                        (int)PTR_ERR(local));
3925                 RETURN(local);
3926         }
3927
3928         /*
3929          * restore i_gid in case S_ISGID is set, we will inherit S_ISGID and set
3930          * correct gid on remote file, not agent here
3931          */
3932         local->i_gid = current_fsgid();
3933         ldiskfs_set_inode_state(local, LDISKFS_STATE_LUSTRE_NOSCRUB);
3934
3935         /* e2fsck doesn't like empty symlinks.  Store remote FID as symlink.
3936          * That gives e2fsck something to look at and be happy, and allows
3937          * debugging if we need to determine where this symlink came from.
3938          */
3939         if (S_ISLNK(type)) {
3940                 CLASSERT(LDISKFS_N_BLOCKS * 4 >= FID_LEN + 1);
3941                 rc = snprintf((char *)LDISKFS_I(local)->i_data,
3942                               LDISKFS_N_BLOCKS * 4, DFID, PFID(fid));
3943
3944                 i_size_write(local, rc);
3945                 LDISKFS_I(local)->i_disksize = rc;
3946         }
3947         unlock_new_inode(local);
3948
3949         /* Agent inode should not have project ID */
3950 #ifdef  HAVE_PROJECT_QUOTA
3951         if (LDISKFS_I(pobj->oo_inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
3952             i_projid_read(pobj->oo_inode) != 0) {
3953                 rc = osd_transfer_project(local, 0, th);
3954                 if (rc) {
3955                         CERROR("%s: quota transfer failed: rc = %d. Is project "
3956                                "quota enforcement enabled on the ldiskfs "
3957                                "filesystem?\n", local->i_sb->s_id, rc);
3958                         RETURN(ERR_PTR(rc));
3959                 }
3960         }
3961 #endif
3962         /* Set special LMA flag for local agent inode */
3963         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
3964         if (rc != 0) {
3965                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
3966                        osd_name(osd), PFID(fid), rc);
3967                 RETURN(ERR_PTR(rc));
3968         }
3969
3970         if (!S_ISDIR(type))
3971                 RETURN(local);
3972
3973         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
3974                                          lu_object_fid(&pobj->oo_dt.do_lu),
3975                                          fid, oh);
3976         if (rc != 0) {
3977                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
3978                         osd_name(osd), PFID(fid), rc);
3979                 RETURN(ERR_PTR(rc));
3980         }
3981
3982         RETURN(local);
3983 }
3984
3985 /**
3986  * when direntry is deleted, we have to take care of possible agent inode
3987  * referenced by that. unfortunately we can't do this at that point:
3988  * iget() within a running transaction leads to deadlock and we better do
3989  * not call that every delete declaration to save performance. so we put
3990  * a potention agent inode on a list and process that once the transaction
3991  * is over. Notice it's not any worse in terms of real orphans as regular
3992  * object destroy doesn't put inodes on the on-disk orphan list. this should
3993  * be addressed separately
3994  */
3995 static int osd_schedule_agent_inode_removal(const struct lu_env *env,
3996                                             struct osd_thandle *oh,
3997                                             __u32 ino)
3998 {
3999         struct osd_device *osd = osd_dt_dev(oh->ot_super.th_dev);
4000         struct osd_obj_orphan *oor;
4001
4002         OBD_ALLOC_PTR(oor);
4003         if (oor == NULL)
4004                 return -ENOMEM;
4005
4006         oor->oor_ino = ino;
4007         oor->oor_env = (struct lu_env *)env;
4008         spin_lock(&osd->od_osfs_lock);
4009         list_add(&oor->oor_list, &osd->od_orphan_list);
4010         spin_unlock(&osd->od_osfs_lock);
4011
4012         oh->ot_remove_agents = 1;
4013
4014         return 0;
4015
4016 }
4017
4018 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
4019                                                 struct osd_device *osd)
4020 {
4021         struct osd_thread_info *info = osd_oti_get(env);
4022         struct osd_obj_orphan *oor, *tmp;
4023         struct osd_inode_id id;
4024         struct list_head list;
4025         struct inode *inode;
4026         struct lu_fid fid;
4027         handle_t *jh;
4028         __u32 ino;
4029
4030         INIT_LIST_HEAD(&list);
4031
4032         spin_lock(&osd->od_osfs_lock);
4033         list_for_each_entry_safe(oor, tmp, &osd->od_orphan_list, oor_list) {
4034                 if (oor->oor_env == env) {
4035                         list_del(&oor->oor_list);
4036                         list_add(&oor->oor_list, &list);
4037                 }
4038         }
4039         spin_unlock(&osd->od_osfs_lock);
4040
4041         list_for_each_entry_safe(oor, tmp, &list, oor_list) {
4042
4043                 ino = oor->oor_ino;
4044
4045                 list_del(&oor->oor_list);
4046                 OBD_FREE_PTR(oor);
4047
4048                 osd_id_gen(&id, ino, OSD_OII_NOGEN);
4049                 inode = osd_iget_fid(info, osd, &id, &fid);
4050                 if (IS_ERR(inode))
4051                         continue;
4052
4053                 if (!osd_remote_fid(env, osd, &fid)) {
4054                         iput(inode);
4055                         continue;
4056                 }
4057
4058                 jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC, 1);
4059                 clear_nlink(inode);
4060                 mark_inode_dirty(inode);
4061                 ldiskfs_journal_stop(jh);
4062                 iput(inode);
4063         }
4064
4065         return 0;
4066 }
4067
4068 /**
4069  * OSD layer object create function for OST objects (b=11826).
4070  *
4071  * The FID is inserted into inode xattr here.
4072  *
4073  * \retval   0, on success
4074  * \retval -ve, on error
4075  */
4076 static int osd_create(const struct lu_env *env, struct dt_object *dt,
4077                       struct lu_attr *attr, struct dt_allocation_hint *hint,
4078                       struct dt_object_format *dof, struct thandle *th)
4079 {
4080         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4081         struct osd_object *obj = osd_dt_obj(dt);
4082         struct osd_thread_info *info = osd_oti_get(env);
4083         int result, on_ost = 0;
4084
4085         ENTRY;
4086
4087         if (dt_object_exists(dt))
4088                 RETURN(-EEXIST);
4089
4090         LINVRNT(osd_invariant(obj));
4091         LASSERT(!dt_object_remote(dt));
4092         LASSERT(osd_is_write_locked(env, obj));
4093         LASSERT(th != NULL);
4094
4095         if (unlikely(fid_is_acct(fid)))
4096                 /*
4097                  * Quota files can't be created from the kernel any more,
4098                  * 'tune2fs -O quota' will take care of creating them
4099                  */
4100                 RETURN(-EPERM);
4101
4102         result = __osd_create(info, obj, attr, hint, dof, th);
4103         if (result == 0) {
4104                 if (fid_is_idif(fid) &&
4105                     !osd_dev(dt->do_lu.lo_dev)->od_index_in_idif) {
4106                         struct lu_fid *tfid = &info->oti_fid;
4107                         struct ost_id *oi   = &info->oti_ostid;
4108
4109                         fid_to_ostid(fid, oi);
4110                         ostid_to_fid(tfid, oi, 0);
4111                         on_ost = 1;
4112                         result = osd_ea_fid_set(info, obj->oo_inode, tfid,
4113                                                 LMAC_FID_ON_OST, 0);
4114                 } else {
4115                         on_ost = fid_is_on_ost(info, osd_obj2dev(obj),
4116                                                fid, OI_CHECK_FLD);
4117                         result = osd_ea_fid_set(info, obj->oo_inode, fid,
4118                                                 on_ost ? LMAC_FID_ON_OST : 0,
4119                                                 0);
4120                 }
4121                 if (obj->oo_dt.do_body_ops == &osd_body_ops_new)
4122                         obj->oo_dt.do_body_ops = &osd_body_ops;
4123         }
4124
4125         if (!result && !CFS_FAIL_CHECK(OBD_FAIL_OSD_NO_OI_ENTRY))
4126                 result = __osd_oi_insert(env, obj, fid, th);
4127
4128         /*
4129          * a small optimization - dt_insert() isn't usually applied
4130          * to OST objects, so we don't need to cache OI mapping for
4131          * OST objects
4132          */
4133         if (result == 0 && on_ost == 0) {
4134                 struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4135
4136                 result = osd_idc_find_and_init(env, osd, obj);
4137                 LASSERT(result == 0);
4138         }
4139
4140         LASSERT(ergo(result == 0,
4141                      dt_object_exists(dt) && !dt_object_remote(dt)));
4142         LINVRNT(osd_invariant(obj));
4143         RETURN(result);
4144 }
4145
4146 static int osd_declare_ref_add(const struct lu_env *env, struct dt_object *dt,
4147                                struct thandle *handle)
4148 {
4149         struct osd_thandle *oh;
4150         int rc;
4151
4152         /* it's possible that object doesn't exist yet */
4153         LASSERT(handle != NULL);
4154
4155         oh = container_of0(handle, struct osd_thandle, ot_super);
4156         LASSERT(oh->ot_handle == NULL);
4157
4158         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
4159                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4160
4161         rc = osd_idc_find_and_init(env, osd_dev(dt->do_lu.lo_dev),
4162                                    osd_dt_obj(dt));
4163
4164         return rc;
4165 }
4166
4167 /*
4168  * Concurrency: @dt is write locked.
4169  */
4170 static int osd_ref_add(const struct lu_env *env, struct dt_object *dt,
4171                        struct thandle *th)
4172 {
4173         struct osd_object *obj = osd_dt_obj(dt);
4174         struct inode *inode = obj->oo_inode;
4175         struct osd_thandle *oh;
4176         int rc = 0;
4177
4178         if (!dt_object_exists(dt) || obj->oo_destroyed)
4179                 return -ENOENT;
4180
4181         LINVRNT(osd_invariant(obj));
4182         LASSERT(!dt_object_remote(dt));
4183         LASSERT(osd_is_write_locked(env, obj));
4184         LASSERT(th != NULL);
4185
4186         oh = container_of0(th, struct osd_thandle, ot_super);
4187         LASSERT(oh->ot_handle != NULL);
4188
4189         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
4190
4191         CDEBUG(D_INODE, DFID" increase nlink %d\n",
4192                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4193         /*
4194          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
4195          * (65000) subdirectories by storing "1" in i_nlink if the link count
4196          * would otherwise overflow. Directory tranversal tools understand
4197          * that (st_nlink == 1) indicates that the filesystem dose not track
4198          * hard links count on the directory, and will not abort subdirectory
4199          * scanning early once (st_nlink - 2) subdirs have been found.
4200          *
4201          * This also has to properly handle the case of inodes with nlink == 0
4202          * in case they are being linked into the PENDING directory
4203          */
4204         spin_lock(&obj->oo_guard);
4205         if (unlikely(inode->i_nlink == 0))
4206                 /* inc_nlink from 0 may cause WARN_ON */
4207                 set_nlink(inode, 1);
4208         else {
4209                 ldiskfs_inc_count(oh->ot_handle, inode);
4210                 if (!S_ISDIR(inode->i_mode))
4211                         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
4212         }
4213         spin_unlock(&obj->oo_guard);
4214
4215         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
4216         LINVRNT(osd_invariant(obj));
4217
4218         osd_trans_exec_check(env, th, OSD_OT_REF_ADD);
4219
4220         return rc;
4221 }
4222
4223 static int osd_declare_ref_del(const struct lu_env *env, struct dt_object *dt,
4224                                struct thandle *handle)
4225 {
4226         struct osd_thandle *oh;
4227
4228         if (!dt_object_exists(dt))
4229                 return -ENOENT;
4230
4231         LASSERT(!dt_object_remote(dt));
4232         LASSERT(handle != NULL);
4233
4234         oh = container_of0(handle, struct osd_thandle, ot_super);
4235         LASSERT(oh->ot_handle == NULL);
4236
4237         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
4238                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4239
4240         return 0;
4241 }
4242
4243 /*
4244  * Concurrency: @dt is write locked.
4245  */
4246 static int osd_ref_del(const struct lu_env *env, struct dt_object *dt,
4247                        struct thandle *th)
4248 {
4249         struct osd_object *obj = osd_dt_obj(dt);
4250         struct inode *inode = obj->oo_inode;
4251         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4252         struct osd_thandle *oh;
4253
4254         if (!dt_object_exists(dt))
4255                 return -ENOENT;
4256
4257         LINVRNT(osd_invariant(obj));
4258         LASSERT(!dt_object_remote(dt));
4259         LASSERT(osd_is_write_locked(env, obj));
4260         LASSERT(th != NULL);
4261
4262         oh = container_of0(th, struct osd_thandle, ot_super);
4263         LASSERT(oh->ot_handle != NULL);
4264
4265         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
4266
4267         spin_lock(&obj->oo_guard);
4268         /*
4269          * That can be result of upgrade from old Lustre version and
4270          * applied only to local files.  Just skip this ref_del call.
4271          * ext4_unlink() only treats this as a warning, don't LASSERT here.
4272          */
4273         if (inode->i_nlink == 0) {
4274                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
4275                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
4276                              ", maybe an upgraded file? (LU-3915)\n",
4277                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
4278                 spin_unlock(&obj->oo_guard);
4279                 return 0;
4280         }
4281
4282         CDEBUG(D_INODE, DFID" decrease nlink %d\n",
4283                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4284
4285         ldiskfs_dec_count(oh->ot_handle, inode);
4286         spin_unlock(&obj->oo_guard);
4287
4288         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
4289         LINVRNT(osd_invariant(obj));
4290
4291         osd_trans_exec_check(env, th, OSD_OT_REF_DEL);
4292
4293         return 0;
4294 }
4295
4296 /*
4297  * Concurrency: @dt is read locked.
4298  */
4299 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
4300                          struct lu_buf *buf, const char *name)
4301 {
4302         struct osd_object      *obj    = osd_dt_obj(dt);
4303         struct inode           *inode  = obj->oo_inode;
4304         struct osd_thread_info *info   = osd_oti_get(env);
4305         struct dentry          *dentry = &info->oti_obj_dentry;
4306         bool cache_xattr = false;
4307         int rc;
4308
4309         LASSERT(buf);
4310
4311         /* version get is not real XATTR but uses xattr API */
4312         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4313                 dt_obj_version_t *ver = buf->lb_buf;
4314
4315                 /*
4316                  * for version we are just using xattr API but change inode
4317                  * field instead
4318                  */
4319                 if (buf->lb_len == 0)
4320                         return sizeof(dt_obj_version_t);
4321
4322                 if (buf->lb_len < sizeof(dt_obj_version_t))
4323                         return -ERANGE;
4324
4325                 CDEBUG(D_INODE, "Get version %#llx for inode %lu\n",
4326                        LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4327
4328                 *ver = LDISKFS_I(inode)->i_fs_version;
4329
4330                 return sizeof(dt_obj_version_t);
4331         }
4332
4333         if (!dt_object_exists(dt))
4334                 return -ENOENT;
4335
4336         LASSERT(!dt_object_remote(dt));
4337         LASSERT(inode->i_op != NULL);
4338 #ifdef HAVE_IOP_XATTR
4339         LASSERT(inode->i_op->getxattr != NULL);
4340 #endif
4341
4342         if (strcmp(name, XATTR_NAME_LOV) == 0 ||
4343             strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
4344                 cache_xattr = true;
4345
4346         if (cache_xattr) {
4347                 rc = osd_oxc_get(obj, name, buf);
4348                 if (rc != -ENOENT)
4349                         return rc;
4350         }
4351
4352         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4353                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4354                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4355                 struct filter_fid *ff;
4356                 struct ost_layout *ol;
4357
4358                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4359                 if (rc)
4360                         return rc;
4361
4362                 LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4363
4364                 rc = sizeof(*ff);
4365                 if (buf->lb_len == 0 || !buf->lb_buf)
4366                         return rc;
4367
4368                 if (buf->lb_len < rc)
4369                         return -ERANGE;
4370
4371                 ff = buf->lb_buf;
4372                 ol = &ff->ff_layout;
4373                 ol->ol_stripe_count = cpu_to_le32(loa->loa_parent_fid.f_ver >>
4374                                                   PFID_STRIPE_IDX_BITS);
4375                 ol->ol_stripe_size = cpu_to_le32(loa->loa_stripe_size);
4376                 loa->loa_parent_fid.f_ver &= PFID_STRIPE_COUNT_MASK;
4377                 fid_cpu_to_le(&ff->ff_parent, &loa->loa_parent_fid);
4378                 if (lma->lma_compat & LMAC_COMP_INFO) {
4379                         ol->ol_comp_start = cpu_to_le64(loa->loa_comp_start);
4380                         ol->ol_comp_end = cpu_to_le64(loa->loa_comp_end);
4381                         ol->ol_comp_id = cpu_to_le32(loa->loa_comp_id);
4382                 } else {
4383                         ol->ol_comp_start = 0;
4384                         ol->ol_comp_end = 0;
4385                         ol->ol_comp_id = 0;
4386                 }
4387         } else {
4388                 rc = __osd_xattr_get(inode, dentry, name,
4389                                      buf->lb_buf, buf->lb_len);
4390         }
4391
4392         if (cache_xattr) {
4393                 if (rc == -ENOENT || rc == -ENODATA)
4394                         osd_oxc_add(obj, name, NULL, 0);
4395                 else if (rc > 0 && buf->lb_buf != NULL)
4396                         osd_oxc_add(obj, name, buf->lb_buf, rc);
4397         }
4398
4399         return rc;
4400 }
4401
4402 static int osd_declare_xattr_set(const struct lu_env *env,
4403                                  struct dt_object *dt,
4404                                  const struct lu_buf *buf, const char *name,
4405                                  int fl, struct thandle *handle)
4406 {
4407         struct osd_thandle *oh;
4408         int credits = 0;
4409         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4410
4411         LASSERT(handle != NULL);
4412
4413         oh = container_of0(handle, struct osd_thandle, ot_super);
4414         LASSERT(oh->ot_handle == NULL);
4415
4416         if (strcmp(name, XATTR_NAME_LMA) == 0) {
4417                 /*
4418                  * For non-upgrading case, the LMA is set first and
4419                  * usually fit inode. But for upgrade case, the LMA
4420                  * may be in another separated EA block.
4421                  */
4422                 if (dt_object_exists(dt)) {
4423                         if (fl == LU_XATTR_REPLACE)
4424                                 credits = 1;
4425                         else
4426                                 goto upgrade;
4427                 }
4428         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4429                 credits = 1;
4430         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
4431                 /* We may need to delete the old PFID EA. */
4432                 credits = LDISKFS_MAXQUOTAS_DEL_BLOCKS(sb);
4433                 if (fl == LU_XATTR_REPLACE)
4434                         credits += 1;
4435                 else
4436                         goto upgrade;
4437         } else {
4438                 /*
4439                  * If some name entry resides on remote MDT, then will create
4440                  * agent entry under remote parent. On the other hand, if the
4441                  * remote entry will be removed, then related agent entry may
4442                  * need to be removed from the remote parent. So there may be
4443                  * kinds of cases, let's declare enough credits. The credits
4444                  * for create agent entry is enough for remove case.
4445                  */
4446                 if (strcmp(name, XATTR_NAME_LINK) == 0) {
4447                         credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
4448                         if (dt_object_exists(dt))
4449                                 credits += 1; /* For updating LMA */
4450                 }
4451
4452 upgrade:
4453                 credits += osd_dto_credits_noquota[DTO_XATTR_SET];
4454
4455                 if (buf != NULL) {
4456                         ssize_t buflen;
4457
4458                         if (buf->lb_buf == NULL && dt_object_exists(dt)) {
4459                                 /*
4460                                  * learn xattr size from osd_xattr_get if
4461                                  * attribute has not been read yet
4462                                  */
4463                                 buflen = __osd_xattr_get(
4464                                     osd_dt_obj(dt)->oo_inode,
4465                                     &osd_oti_get(env)->oti_obj_dentry,
4466                                     name, NULL, 0);
4467                                 if (buflen < 0)
4468                                         buflen = 0;
4469                         } else {
4470                                 buflen = buf->lb_len;
4471                         }
4472
4473                         if (buflen > sb->s_blocksize) {
4474                                 credits += osd_calc_bkmap_credits(
4475                                     sb, NULL, 0, -1,
4476                                     (buflen + sb->s_blocksize - 1) >>
4477                                     sb->s_blocksize_bits);
4478                         }
4479                 }
4480                 /*
4481                  * xattr set may involve inode quota change, reserve credits for
4482                  * dquot_initialize()
4483                  */
4484                 credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4485         }
4486
4487         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
4488
4489         return 0;
4490 }
4491
4492 static int osd_xattr_set_pfid(const struct lu_env *env, struct osd_object *obj,
4493                               const struct lu_buf *buf, int fl,
4494                               struct thandle *handle)
4495 {
4496         struct osd_thread_info *info = osd_oti_get(env);
4497         struct dentry *dentry = &info->oti_obj_dentry;
4498         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4499         struct lustre_mdt_attrs *lma = &loa->loa_lma;
4500         struct inode *inode = obj->oo_inode;
4501         struct filter_fid *ff = buf->lb_buf;
4502         struct ost_layout *ol = &ff->ff_layout;
4503         int flags = XATTR_REPLACE;
4504         int rc;
4505
4506         ENTRY;
4507
4508         if (buf->lb_len != sizeof(*ff) && buf->lb_len != sizeof(struct lu_fid))
4509                 RETURN(-EINVAL);
4510
4511         rc = osd_get_lma(info, inode, dentry, loa);
4512         if (rc == -ENODATA) {
4513                 /* Usually for upgarding from old device */
4514                 lustre_loa_init(loa, lu_object_fid(&obj->oo_dt.do_lu),
4515                                 LMAC_FID_ON_OST, 0);
4516                 flags = XATTR_CREATE;
4517         } else if (rc) {
4518                 RETURN(rc);
4519         }
4520
4521         if (!rc && lma->lma_compat & LMAC_STRIPE_INFO) {
4522                 if ((fl & LU_XATTR_CREATE) && !(fl & LU_XATTR_REPLACE))
4523                         RETURN(-EEXIST);
4524
4525                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256) {
4526                         /* Separate PFID EA from LMA */
4527                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4528                         lustre_lma_swab(lma);
4529                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4530                                              sizeof(*lma), XATTR_REPLACE);
4531                         if (!rc) {
4532                                 obj->oo_pfid_in_lma = 0;
4533                                 rc = LU_XATTR_CREATE;
4534                         }
4535
4536                         RETURN(rc);
4537                 }
4538         } else {
4539                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256)
4540                         RETURN(fl);
4541
4542                 /*
4543                  * Old client does not send stripe information,
4544                  * then store the PFID EA on disk separatedly.
4545                  */
4546                 if (unlikely(buf->lb_len == sizeof(struct lu_fid) ||
4547                              ol->ol_stripe_size == 0))
4548                         RETURN(fl);
4549
4550                 /* Remove old PFID EA entry firstly. */
4551                 ll_vfs_dq_init(inode);
4552                 rc = osd_removexattr(dentry, inode, XATTR_NAME_FID);
4553                 if (rc == -ENODATA) {
4554                         if ((fl & LU_XATTR_REPLACE) && !(fl & LU_XATTR_CREATE))
4555                                 RETURN(rc);
4556                 } else if (rc) {
4557                         RETURN(rc);
4558                 }
4559         }
4560
4561         fid_le_to_cpu(&loa->loa_parent_fid, &ff->ff_parent);
4562         if (likely(ol->ol_stripe_size != 0)) {
4563                 loa->loa_parent_fid.f_ver |= le32_to_cpu(ol->ol_stripe_count) <<
4564                                              PFID_STRIPE_IDX_BITS;
4565                 loa->loa_stripe_size = le32_to_cpu(ol->ol_stripe_size);
4566                 lma->lma_compat |= LMAC_STRIPE_INFO;
4567                 if (ol->ol_comp_id != 0) {
4568                         loa->loa_comp_id = le32_to_cpu(ol->ol_comp_id);
4569                         loa->loa_comp_start = le64_to_cpu(ol->ol_comp_start);
4570                         loa->loa_comp_end = le64_to_cpu(ol->ol_comp_end);
4571                         lma->lma_compat |= LMAC_COMP_INFO;
4572                 }
4573         }
4574
4575         lustre_loa_swab(loa, false);
4576
4577         /* Store the PFID EA inside LMA. */
4578         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa, sizeof(*loa),
4579                              flags);
4580         if (!rc)
4581                 obj->oo_pfid_in_lma = 1;
4582
4583         RETURN(rc);
4584 }
4585
4586 /*
4587  * In DNE environment, the object (in spite of regular file or directory)
4588  * and its name entry may reside on different MDTs. Under such case, we will
4589  * create an agent entry on the MDT where the object resides. The agent entry
4590  * references the object locally, that makes the object to be visible to the
4591  * userspace when mounted as 'ldiskfs' directly. Then the userspace tools,
4592  * such as 'tar' can handle the object properly.
4593  *
4594  * We handle the agent entry during set linkEA that is the common interface
4595  * for both regular file and directroy, can handle kinds of cases, such as
4596  * create/link/unlink/rename, and so on.
4597  *
4598  * NOTE: we can NOT do that when ea_{insert,delete} that is only for directory.
4599  *
4600  * XXX: There are two known issues:
4601  * 1. For one object, we will create at most one agent entry even if there
4602  *    may be more than one cross-MDTs hard links on the object. So the local
4603  *    e2fsck may claim that the object's nlink is larger than the name entries
4604  *    that reference such inode. And in further, the e2fsck will fix the nlink
4605  *    attribute to match the local references. Then it will cause the object's
4606  *    nlink attribute to be inconsistent with the global references. it is bad
4607  *    but not fatal. The ref_del() can handle the zero-referenced case. On the
4608  *    other hand, the global namespace LFSCK can repair the object's attribute
4609  *    according to the linkEA.
4610  * 2. There may be too many hard links on the object as to its linkEA overflow,
4611  *    then the linkEA entry for cross-MDTs reference may be discarded. If such
4612  *    case happened, then at this point, we do not know whether there are some
4613  *    cross-MDTs reference. But there are local references, it guarantees that
4614  *    object is visible to userspace when mounted as 'ldiskfs'. That is enough.
4615  */
4616 static int osd_xattr_handle_linkea(const struct lu_env *env,
4617                                    struct osd_device *osd,
4618                                    struct osd_object *obj,
4619                                    const struct lu_buf *buf,
4620                                    struct thandle *handle)
4621 {
4622         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
4623         struct lu_fid *tfid = &osd_oti_get(env)->oti_fid3;
4624         struct linkea_data ldata = { .ld_buf = (struct lu_buf *)buf };
4625         struct lu_name tmpname;
4626         struct osd_thandle *oh;
4627         int rc;
4628         bool remote = false;
4629
4630         ENTRY;
4631
4632         oh = container_of0(handle, struct osd_thandle, ot_super);
4633         LASSERT(oh->ot_handle != NULL);
4634
4635         rc = linkea_init_with_rec(&ldata);
4636         if (!rc) {
4637                 linkea_first_entry(&ldata);
4638                 while (ldata.ld_lee != NULL && !remote) {
4639                         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen,
4640                                             &tmpname, tfid);
4641                         if (osd_remote_fid(env, osd, tfid) > 0)
4642                                 remote = true;
4643                         else
4644                                 linkea_next_entry(&ldata);
4645                 }
4646         } else if (rc == -ENODATA) {
4647                 rc = 0;
4648         } else {
4649                 RETURN(rc);
4650         }
4651
4652         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu) && !remote) {
4653                 rc = osd_delete_from_remote_parent(env, osd, obj, oh, false);
4654                 if (rc)
4655                         CERROR("%s: failed to remove agent entry for "DFID
4656                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4657         } else if (!lu_object_has_agent_entry(&obj->oo_dt.do_lu) && remote) {
4658                 rc = osd_add_to_remote_parent(env, osd, obj, oh);
4659                 if (rc)
4660                         CERROR("%s: failed to create agent entry for "DFID
4661                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4662         }
4663
4664         RETURN(rc);
4665 }
4666
4667 /*
4668  * Concurrency: @dt is write locked.
4669  */
4670 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
4671                          const struct lu_buf *buf, const char *name, int fl,
4672                          struct thandle *handle)
4673 {
4674         struct osd_object *obj = osd_dt_obj(dt);
4675         struct osd_device *osd = osd_obj2dev(obj);
4676         struct inode *inode = obj->oo_inode;
4677         struct osd_thread_info *info = osd_oti_get(env);
4678         int fs_flags = 0;
4679         int len;
4680         int rc;
4681
4682         ENTRY;
4683
4684         LASSERT(handle);
4685         LASSERT(buf);
4686
4687         /* version set is not real XATTR */
4688         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4689                 dt_obj_version_t *version = buf->lb_buf;
4690
4691                 /*
4692                  * for version we are just using xattr API but change inode
4693                  * field instead
4694                  */
4695                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
4696
4697                 CDEBUG(D_INODE, "Set version %#llx (old %#llx) for inode %lu\n",
4698                        *version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4699
4700                 LDISKFS_I(inode)->i_fs_version = *version;
4701                 /*
4702                  * Version is set after all inode operations are finished,
4703                  * so we should mark it dirty here
4704                  */
4705                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
4706
4707                 RETURN(0);
4708         }
4709
4710         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zu\n",
4711                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
4712
4713         len = buf->lb_len;
4714         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4715
4716         /*
4717          * For the OST device with 256 bytes inode size by default,
4718          * the PFID EA will be stored together with LMA EA to avoid
4719          * performance trouble. Otherwise the PFID EA can be stored
4720          * independently. LU-8998
4721          */
4722         if (strcmp(name, XATTR_NAME_FID) == 0 && osd->od_is_ost &&
4723             (LDISKFS_INODE_SIZE(inode->i_sb) <= 256 || obj->oo_pfid_in_lma)) {
4724                 LASSERT(buf->lb_buf);
4725
4726                 fl = osd_xattr_set_pfid(env, obj, buf, fl, handle);
4727                 if (fl <= 0)
4728                         RETURN(fl);
4729         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
4730                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4731                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4732
4733                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4734                 if (rc)
4735                         RETURN(rc);
4736
4737                 lma->lma_incompat |= LMAI_STRIPED;
4738                 lustre_lma_swab(lma);
4739                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4740                                      sizeof(*lma), XATTR_REPLACE);
4741                 if (rc != 0)
4742                         RETURN(rc);
4743         } else if (strcmp(name, XATTR_NAME_LINK) == 0) {
4744                 LASSERT(!osd->od_is_ost);
4745
4746                 rc = osd_xattr_handle_linkea(env, osd, obj, buf, handle);
4747                 if (rc)
4748                         RETURN(rc);
4749         }
4750
4751         if (fl & LU_XATTR_REPLACE)
4752                 fs_flags |= XATTR_REPLACE;
4753
4754         if (fl & LU_XATTR_CREATE)
4755                 fs_flags |= XATTR_CREATE;
4756
4757         rc = __osd_xattr_set(info, inode, name, buf->lb_buf, len, fs_flags);
4758         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4759
4760         if (rc == 0 &&
4761             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4762              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4763                 osd_oxc_add(obj, name, buf->lb_buf, buf->lb_len);
4764
4765         return rc;
4766 }
4767
4768 /*
4769  * Concurrency: @dt is read locked.
4770  */
4771 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
4772                           const struct lu_buf *buf)
4773 {
4774         struct osd_object *obj = osd_dt_obj(dt);
4775         struct inode *inode = obj->oo_inode;
4776         struct osd_thread_info *info = osd_oti_get(env);
4777         struct dentry *dentry = &info->oti_obj_dentry;
4778
4779         if (!dt_object_exists(dt))
4780                 return -ENOENT;
4781
4782         LASSERT(!dt_object_remote(dt));
4783         LASSERT(inode->i_op != NULL);
4784         LASSERT(inode->i_op->listxattr != NULL);
4785
4786         dentry->d_inode = inode;
4787         dentry->d_sb = inode->i_sb;
4788         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
4789 }
4790
4791 static int osd_declare_xattr_del(const struct lu_env *env,
4792                                  struct dt_object *dt, const char *name,
4793                                  struct thandle *handle)
4794 {
4795         struct osd_thandle *oh;
4796         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4797
4798         LASSERT(!dt_object_remote(dt));
4799         LASSERT(handle != NULL);
4800
4801         oh = container_of0(handle, struct osd_thandle, ot_super);
4802         LASSERT(oh->ot_handle == NULL);
4803
4804         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
4805                              osd_dto_credits_noquota[DTO_XATTR_SET]);
4806         /*
4807          * xattr del may involve inode quota change, reserve credits for
4808          * dquot_initialize()
4809          */
4810         oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4811
4812         return 0;
4813 }
4814
4815 /*
4816  * Concurrency: @dt is write locked.
4817  */
4818 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
4819                          const char *name, struct thandle *handle)
4820 {
4821         struct osd_object *obj = osd_dt_obj(dt);
4822         struct inode *inode = obj->oo_inode;
4823         struct osd_thread_info *info = osd_oti_get(env);
4824         struct dentry *dentry = &info->oti_obj_dentry;
4825         int rc;
4826
4827         if (!dt_object_exists(dt))
4828                 return -ENOENT;
4829
4830         LASSERT(!dt_object_remote(dt));
4831         LASSERT(inode->i_op != NULL);
4832         LASSERT(handle != NULL);
4833 #ifdef HAVE_IOP_XATTR
4834         LASSERT(inode->i_op->removexattr != NULL);
4835 #endif
4836
4837         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4838
4839         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4840                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
4841
4842                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
4843                                  &info->oti_ost_attrs);
4844                 if (!rc) {
4845                         LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4846
4847                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4848                         lustre_lma_swab(lma);
4849                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4850                                              sizeof(*lma), XATTR_REPLACE);
4851                         if (!rc)
4852                                 obj->oo_pfid_in_lma = 0;
4853                 }
4854         } else {
4855                 ll_vfs_dq_init(inode);
4856                 dentry->d_inode = inode;
4857                 dentry->d_sb = inode->i_sb;
4858                 rc = osd_removexattr(dentry, inode, name);
4859         }
4860
4861         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4862
4863         if (rc == 0 &&
4864             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4865              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4866                 osd_oxc_del(obj, name);
4867
4868         return rc;
4869 }
4870
4871 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt,
4872                            __u64 start, __u64 end)
4873 {
4874         struct osd_object *obj = osd_dt_obj(dt);
4875         struct inode *inode = obj->oo_inode;
4876         struct osd_thread_info *info = osd_oti_get(env);
4877         struct dentry *dentry = &info->oti_obj_dentry;
4878         struct file *file = &info->oti_file;
4879         int rc;
4880
4881         ENTRY;
4882
4883         dentry->d_inode = inode;
4884         dentry->d_sb = inode->i_sb;
4885         file->f_path.dentry = dentry;
4886         file->f_mapping = inode->i_mapping;
4887         file->f_op = inode->i_fop;
4888         set_file_inode(file, inode);
4889
4890         rc = ll_vfs_fsync_range(file, start, end, 0);
4891
4892         RETURN(rc);
4893 }
4894
4895 static int osd_invalidate(const struct lu_env *env, struct dt_object *dt)
4896 {
4897         return 0;
4898 }
4899
4900 /*
4901  * Index operations.
4902  */
4903
4904 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
4905                                const struct dt_index_features *feat)
4906 {
4907         struct iam_descr *descr;
4908
4909         if (osd_object_is_root(o))
4910                 return feat == &dt_directory_features;
4911
4912         LASSERT(o->oo_dir != NULL);
4913
4914         descr = o->oo_dir->od_container.ic_descr;
4915         if (feat == &dt_directory_features) {
4916                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
4917                         return 1;
4918                 else
4919                         return 0;
4920         } else {
4921                 return feat->dif_keysize_min <= descr->id_key_size &&
4922                        descr->id_key_size <= feat->dif_keysize_max &&
4923                        feat->dif_recsize_min <= descr->id_rec_size &&
4924                        descr->id_rec_size <= feat->dif_recsize_max &&
4925                        !(feat->dif_flags & (DT_IND_VARKEY |
4926                                             DT_IND_VARREC | DT_IND_NONUNQ)) &&
4927                        ergo(feat->dif_flags & DT_IND_UPDATE,
4928                             1 /* XXX check that object (and fs) is writable */);
4929         }
4930 }
4931
4932 static int osd_iam_container_init(const struct lu_env *env,
4933                                   struct osd_object *obj,
4934                                   struct osd_directory *dir)
4935 {
4936         struct iam_container *bag = &dir->od_container;
4937         int result;
4938
4939         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
4940         if (result != 0)
4941                 return result;
4942
4943         result = iam_container_setup(bag);
4944         if (result == 0)
4945                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
4946         else
4947                 iam_container_fini(bag);
4948
4949         return result;
4950 }
4951
4952
4953 /*
4954  * Concurrency: no external locking is necessary.
4955  */
4956 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
4957                          const struct dt_index_features *feat)
4958 {
4959         int result;
4960         int skip_iam = 0;
4961         struct osd_object *obj = osd_dt_obj(dt);
4962
4963         LINVRNT(osd_invariant(obj));
4964
4965         if (osd_object_is_root(obj)) {
4966                 dt->do_index_ops = &osd_index_ea_ops;
4967                 result = 0;
4968         } else if (feat == &dt_directory_features) {
4969                 dt->do_index_ops = &osd_index_ea_ops;
4970                 if (obj->oo_inode == NULL || S_ISDIR(obj->oo_inode->i_mode))
4971                         result = 0;
4972                 else
4973                         result = -ENOTDIR;
4974                 skip_iam = 1;
4975         } else if (unlikely(feat == &dt_otable_features)) {
4976                 dt->do_index_ops = &osd_otable_ops;
4977                 return 0;
4978         } else if (unlikely(feat == &dt_acct_features)) {
4979                 dt->do_index_ops = &osd_acct_index_ops;
4980                 result = 0;
4981                 skip_iam = 1;
4982         } else if (!osd_has_index(obj)) {
4983                 struct osd_directory *dir;
4984                 struct osd_device *osd = osd_obj2dev(obj);
4985                 const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4986
4987                 OBD_ALLOC_PTR(dir);
4988                 if (dir) {
4989
4990                         spin_lock(&obj->oo_guard);
4991                         if (obj->oo_dir == NULL)
4992                                 obj->oo_dir = dir;
4993                         else
4994                                 /*
4995                                  * Concurrent thread allocated container data.
4996                                  */
4997                                 OBD_FREE_PTR(dir);
4998                         spin_unlock(&obj->oo_guard);
4999                         /*
5000                          * Now, that we have container data, serialize its
5001                          * initialization.
5002                          */
5003                         down_write(&obj->oo_ext_idx_sem);
5004                         /*
5005                          * recheck under lock.
5006                          */
5007
5008                         if (osd_has_index(obj)) {
5009                                 result = 0;
5010                                 goto unlock;
5011                         }
5012
5013                         result = osd_iam_container_init(env, obj, obj->oo_dir);
5014                         if (result || feat == &dt_lfsck_namespace_features ||
5015                             feat == &dt_lfsck_layout_orphan_features ||
5016                             feat == &dt_lfsck_layout_dangling_features)
5017                                 goto unlock;
5018
5019                         result = osd_index_register(osd, fid,
5020                                                     feat->dif_keysize_max,
5021                                                     feat->dif_recsize_max);
5022                         if (result < 0)
5023                                 CWARN("%s: failed to register index "
5024                                       DFID": rc = %d\n",
5025                                       osd_name(osd), PFID(fid), result);
5026                         else if (result > 0)
5027                                 result = 0;
5028                         else
5029                                 CDEBUG(D_LFSCK, "%s: index object "DFID
5030                                        " (%d/%d) registered\n",
5031                                        osd_name(osd), PFID(fid),
5032                                        (int)feat->dif_keysize_max,
5033                                        (int)feat->dif_recsize_max);
5034
5035 unlock:
5036                         up_write(&obj->oo_ext_idx_sem);
5037                 } else {
5038                         result = -ENOMEM;
5039                 }
5040         } else {
5041                 result = 0;
5042         }
5043
5044         if (result == 0 && skip_iam == 0) {
5045                 if (!osd_iam_index_probe(env, obj, feat))
5046                         result = -ENOTDIR;
5047         }
5048         LINVRNT(osd_invariant(obj));
5049
5050         return result;
5051 }
5052
5053 static int osd_otable_it_attr_get(const struct lu_env *env,
5054                                  struct dt_object *dt,
5055                                  struct lu_attr *attr)
5056 {
5057         attr->la_valid = 0;
5058         return 0;
5059 }
5060
5061 static const struct dt_object_operations osd_obj_ops = {
5062         .do_read_lock           = osd_read_lock,
5063         .do_write_lock          = osd_write_lock,
5064         .do_read_unlock         = osd_read_unlock,
5065         .do_write_unlock        = osd_write_unlock,
5066         .do_write_locked        = osd_write_locked,
5067         .do_attr_get            = osd_attr_get,
5068         .do_declare_attr_set    = osd_declare_attr_set,
5069         .do_attr_set            = osd_attr_set,
5070         .do_ah_init             = osd_ah_init,
5071         .do_declare_create      = osd_declare_create,
5072         .do_create              = osd_create,
5073         .do_declare_destroy     = osd_declare_destroy,
5074         .do_destroy             = osd_destroy,
5075         .do_index_try           = osd_index_try,
5076         .do_declare_ref_add     = osd_declare_ref_add,
5077         .do_ref_add             = osd_ref_add,
5078         .do_declare_ref_del     = osd_declare_ref_del,
5079         .do_ref_del             = osd_ref_del,
5080         .do_xattr_get           = osd_xattr_get,
5081         .do_declare_xattr_set   = osd_declare_xattr_set,
5082         .do_xattr_set           = osd_xattr_set,
5083         .do_declare_xattr_del   = osd_declare_xattr_del,
5084         .do_xattr_del           = osd_xattr_del,
5085         .do_xattr_list          = osd_xattr_list,
5086         .do_object_sync         = osd_object_sync,
5087         .do_invalidate          = osd_invalidate,
5088 };
5089
5090 static const struct dt_object_operations osd_obj_otable_it_ops = {
5091         .do_attr_get    = osd_otable_it_attr_get,
5092         .do_index_try   = osd_index_try,
5093 };
5094
5095 static int osd_index_declare_iam_delete(const struct lu_env *env,
5096                                         struct dt_object *dt,
5097                                         const struct dt_key *key,
5098                                         struct thandle *handle)
5099 {
5100         struct osd_thandle *oh;
5101
5102         oh = container_of0(handle, struct osd_thandle, ot_super);
5103         LASSERT(oh->ot_handle == NULL);
5104
5105         /* Recycle  may cause additional three blocks to be changed. */
5106         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
5107                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
5108
5109         return 0;
5110 }
5111
5112 /**
5113  *      delete a (key, value) pair from index \a dt specified by \a key
5114  *
5115  *      \param  dt      osd index object
5116  *      \param  key     key for index
5117  *      \param  rec     record reference
5118  *      \param  handle  transaction handler
5119  *
5120  *      \retval  0  success
5121  *      \retval -ve   failure
5122  */
5123 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
5124                                 const struct dt_key *key,
5125                                 struct thandle *handle)
5126 {
5127         struct osd_thread_info *oti = osd_oti_get(env);
5128         struct osd_object *obj = osd_dt_obj(dt);
5129         struct osd_thandle *oh;
5130         struct iam_path_descr *ipd;
5131         struct iam_container *bag = &obj->oo_dir->od_container;
5132         int rc;
5133
5134         ENTRY;
5135
5136         if (!dt_object_exists(dt))
5137                 RETURN(-ENOENT);
5138
5139         LINVRNT(osd_invariant(obj));
5140         LASSERT(!dt_object_remote(dt));
5141         LASSERT(bag->ic_object == obj->oo_inode);
5142         LASSERT(handle != NULL);
5143
5144         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5145
5146         ipd = osd_idx_ipd_get(env, bag);
5147         if (unlikely(ipd == NULL))
5148                 RETURN(-ENOMEM);
5149
5150         oh = container_of0(handle, struct osd_thandle, ot_super);
5151         LASSERT(oh->ot_handle != NULL);
5152         LASSERT(oh->ot_handle->h_transaction != NULL);
5153
5154         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5155                 /* swab quota uid/gid provided by caller */
5156                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5157                 key = (const struct dt_key *)&oti->oti_quota_id;
5158         }
5159
5160         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
5161         osd_ipd_put(env, bag, ipd);
5162         LINVRNT(osd_invariant(obj));
5163         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5164         RETURN(rc);
5165 }
5166
5167 static int osd_index_declare_ea_delete(const struct lu_env *env,
5168                                        struct dt_object *dt,
5169                                        const struct dt_key *key,
5170                                        struct thandle *handle)
5171 {
5172         struct osd_thandle *oh;
5173         struct inode *inode;
5174         int rc, credits;
5175
5176         ENTRY;
5177
5178         LASSERT(!dt_object_remote(dt));
5179         LASSERT(handle != NULL);
5180
5181         oh = container_of0(handle, struct osd_thandle, ot_super);
5182         LASSERT(oh->ot_handle == NULL);
5183
5184         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE];
5185         osd_trans_declare_op(env, oh, OSD_OT_DELETE, credits);
5186
5187         inode = osd_dt_obj(dt)->oo_inode;
5188         if (inode == NULL)
5189                 RETURN(-ENOENT);
5190
5191         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
5192                                    i_projid_read(inode), 0, oh, osd_dt_obj(dt),
5193                                    NULL, OSD_QID_BLK);
5194         RETURN(rc);
5195 }
5196
5197 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
5198                                           struct dt_rec *fid)
5199 {
5200         struct osd_fid_pack *rec;
5201         int rc = -ENODATA;
5202
5203         if (de->file_type & LDISKFS_DIRENT_LUFID) {
5204                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
5205                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
5206                 if (rc == 0 && unlikely(!fid_is_sane((struct lu_fid *)fid)))
5207                         rc = -EINVAL;
5208         }
5209         return rc;
5210 }
5211
5212 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
5213                           const struct lu_fid *fid)
5214 {
5215         struct seq_server_site *ss = osd_seq_site(osd);
5216
5217         ENTRY;
5218
5219         /* FID seqs not in FLDB, must be local seq */
5220         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
5221                 RETURN(0);
5222
5223         /*
5224          * If FLD is not being initialized yet, it only happens during the
5225          * initialization, likely during mgs initialization, and we assume
5226          * this is local FID.
5227          */
5228         if (ss == NULL || ss->ss_server_fld == NULL)
5229                 RETURN(0);
5230
5231         /* Only check the local FLDB here */
5232         if (osd_seq_exists(env, osd, fid_seq(fid)))
5233                 RETURN(0);
5234
5235         RETURN(1);
5236 }
5237
5238 static void osd_take_care_of_agent(const struct lu_env *env,
5239                                    struct osd_device *osd,
5240                                    struct osd_thandle *oh,
5241                                    struct ldiskfs_dir_entry_2 *de)
5242 {
5243         struct lu_fid *fid = &osd_oti_get(env)->oti_fid;
5244         struct osd_idmap_cache *idc;
5245         int rc, schedule = 0;
5246
5247         LASSERT(de != NULL);
5248
5249         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
5250         if (likely(rc == 0)) {
5251                 idc = osd_idc_find_or_init(env, osd, fid);
5252                 if (IS_ERR(idc) || idc->oic_remote)
5253                         schedule = 1;
5254         } else if (rc == -ENODATA) {
5255                 /*
5256                  * can't get FID, postpone to the end of the
5257                  * transaction when iget() is safe
5258                  */
5259                 schedule = 1;
5260         } else {
5261                 CERROR("%s: can't get FID: rc = %d\n", osd_name(osd), rc);
5262         }
5263         if (schedule)
5264                 osd_schedule_agent_inode_removal(env, oh,
5265                                                  le32_to_cpu(de->inode));
5266 }
5267
5268 /**
5269  * Index delete function for interoperability mode (b11826).
5270  * It will remove the directory entry added by osd_index_ea_insert().
5271  * This entry is needed to maintain name->fid mapping.
5272  *
5273  * \param key,  key i.e. file entry to be deleted
5274  *
5275  * \retval   0, on success
5276  * \retval -ve, on error
5277  */
5278 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
5279                                const struct dt_key *key, struct thandle *handle)
5280 {
5281         struct osd_object *obj = osd_dt_obj(dt);
5282         struct inode *dir = obj->oo_inode;
5283         struct dentry *dentry;
5284         struct osd_thandle *oh;
5285         struct ldiskfs_dir_entry_2 *de = NULL;
5286         struct buffer_head *bh;
5287         struct htree_lock *hlock = NULL;
5288         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
5289         int rc;
5290
5291         ENTRY;
5292
5293         if (!dt_object_exists(dt))
5294                 RETURN(-ENOENT);
5295
5296         LINVRNT(osd_invariant(obj));
5297         LASSERT(!dt_object_remote(dt));
5298         LASSERT(handle != NULL);
5299
5300         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5301
5302         oh = container_of(handle, struct osd_thandle, ot_super);
5303         LASSERT(oh->ot_handle != NULL);
5304         LASSERT(oh->ot_handle->h_transaction != NULL);
5305
5306         ll_vfs_dq_init(dir);
5307         dentry = osd_child_dentry_get(env, obj,
5308                                       (char *)key, strlen((char *)key));
5309
5310         if (obj->oo_hl_head != NULL) {
5311                 hlock = osd_oti_get(env)->oti_hlock;
5312                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5313                                    dir, LDISKFS_HLOCK_DEL);
5314         } else {
5315                 down_write(&obj->oo_ext_idx_sem);
5316         }
5317
5318         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5319         if (!IS_ERR(bh)) {
5320                 /*
5321                  * If this is not the ".." entry, it might be a remote DNE
5322                  * entry and  we need to check if the FID is for a remote
5323                  * MDT.  If the FID is  not in the directory entry (e.g.
5324                  * upgraded 1.8 filesystem without dirdata enabled) then
5325                  * we need to get the FID from the LMA. For a remote directory
5326                  * there HAS to be an LMA, it cannot be an IGIF inode in this
5327                  * case.
5328                  *
5329                  * Delete the entry before the agent inode in order to
5330                  * simplify error handling.  At worst an error after deleting
5331                  * the entry first might leak the agent inode afterward. The
5332                  * reverse would need filesystem abort in case of error deleting
5333                  * the entry after the agent had been removed, or leave a
5334                  * dangling entry pointing at a random inode.
5335                  */
5336                 if (strcmp((char *)key, dotdot) != 0)
5337                         osd_take_care_of_agent(env, osd, oh, de);
5338                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
5339                 brelse(bh);
5340         } else {
5341                 rc = PTR_ERR(bh);
5342         }
5343         if (hlock != NULL)
5344                 ldiskfs_htree_unlock(hlock);
5345         else
5346                 up_write(&obj->oo_ext_idx_sem);
5347
5348         GOTO(out, rc);
5349 out:
5350         LASSERT(osd_invariant(obj));
5351         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5352         RETURN(rc);
5353 }
5354
5355 /**
5356  *      Lookup index for \a key and copy record to \a rec.
5357  *
5358  *      \param  dt      osd index object
5359  *      \param  key     key for index
5360  *      \param  rec     record reference
5361  *
5362  *      \retval  +ve  success : exact mach
5363  *      \retval  0    return record with key not greater than \a key
5364  *      \retval -ve   failure
5365  */
5366 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
5367                                 struct dt_rec *rec, const struct dt_key *key)
5368 {
5369         struct osd_object *obj = osd_dt_obj(dt);
5370         struct iam_path_descr *ipd;
5371         struct iam_container *bag = &obj->oo_dir->od_container;
5372         struct osd_thread_info *oti = osd_oti_get(env);
5373         struct iam_iterator *it = &oti->oti_idx_it;
5374         struct iam_rec *iam_rec;
5375         int rc;
5376
5377         ENTRY;
5378
5379         if (!dt_object_exists(dt))
5380                 RETURN(-ENOENT);
5381
5382         LASSERT(osd_invariant(obj));
5383         LASSERT(!dt_object_remote(dt));
5384         LASSERT(bag->ic_object == obj->oo_inode);
5385
5386         ipd = osd_idx_ipd_get(env, bag);
5387         if (IS_ERR(ipd))
5388                 RETURN(-ENOMEM);
5389
5390         /* got ipd now we can start iterator. */
5391         iam_it_init(it, bag, 0, ipd);
5392
5393         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5394                 /* swab quota uid/gid provided by caller */
5395                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5396                 key = (const struct dt_key *)&oti->oti_quota_id;
5397         }
5398
5399         rc = iam_it_get(it, (struct iam_key *)key);
5400         if (rc >= 0) {
5401                 if (S_ISDIR(obj->oo_inode->i_mode))
5402                         iam_rec = (struct iam_rec *)oti->oti_ldp;
5403                 else
5404                         iam_rec = (struct iam_rec *)rec;
5405
5406                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
5407
5408                 if (S_ISDIR(obj->oo_inode->i_mode))
5409                         osd_fid_unpack((struct lu_fid *)rec,
5410                                        (struct osd_fid_pack *)iam_rec);
5411                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
5412                         osd_quota_unpack(obj, rec);
5413         }
5414
5415         iam_it_put(it);
5416         iam_it_fini(it);
5417         osd_ipd_put(env, bag, ipd);
5418
5419         LINVRNT(osd_invariant(obj));
5420
5421         RETURN(rc);
5422 }
5423
5424 static int osd_index_declare_iam_insert(const struct lu_env *env,
5425                                         struct dt_object *dt,
5426                                         const struct dt_rec *rec,
5427                                         const struct dt_key *key,
5428                                         struct thandle *handle)
5429 {
5430         struct osd_thandle *oh;
5431
5432         LASSERT(handle != NULL);
5433
5434         oh = container_of0(handle, struct osd_thandle, ot_super);
5435         LASSERT(oh->ot_handle == NULL);
5436
5437         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
5438                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
5439
5440         return 0;
5441 }
5442
5443 /**
5444  *      Inserts (key, value) pair in \a dt index object.
5445  *
5446  *      \param  dt      osd index object
5447  *      \param  key     key for index
5448  *      \param  rec     record reference
5449  *      \param  th      transaction handler
5450  *
5451  *      \retval  0  success
5452  *      \retval -ve failure
5453  */
5454 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
5455                                 const struct dt_rec *rec,
5456                                 const struct dt_key *key, struct thandle *th)
5457 {
5458         struct osd_object *obj = osd_dt_obj(dt);
5459         struct iam_path_descr *ipd;
5460         struct osd_thandle *oh;
5461         struct iam_container *bag;
5462         struct osd_thread_info *oti = osd_oti_get(env);
5463         struct iam_rec *iam_rec;
5464         int rc;
5465
5466         ENTRY;
5467
5468         if (!dt_object_exists(dt))
5469                 RETURN(-ENOENT);
5470
5471         LINVRNT(osd_invariant(obj));
5472         LASSERT(!dt_object_remote(dt));
5473
5474         bag = &obj->oo_dir->od_container;
5475         LASSERT(bag->ic_object == obj->oo_inode);
5476         LASSERT(th != NULL);
5477
5478         osd_trans_exec_op(env, th, OSD_OT_INSERT);
5479
5480         ipd = osd_idx_ipd_get(env, bag);
5481         if (unlikely(ipd == NULL))
5482                 RETURN(-ENOMEM);
5483
5484         oh = container_of0(th, struct osd_thandle, ot_super);
5485         LASSERT(oh->ot_handle != NULL);
5486         LASSERT(oh->ot_handle->h_transaction != NULL);
5487         if (S_ISDIR(obj->oo_inode->i_mode)) {
5488                 iam_rec = (struct iam_rec *)oti->oti_ldp;
5489                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec,
5490                              &oti->oti_fid);
5491         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5492                 /* pack quota uid/gid */
5493                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5494                 key = (const struct dt_key *)&oti->oti_quota_id;
5495                 /* pack quota record */
5496                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
5497                 iam_rec = (struct iam_rec *)rec;
5498         } else {
5499                 iam_rec = (struct iam_rec *)rec;
5500         }
5501
5502         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
5503                         iam_rec, ipd);
5504         osd_ipd_put(env, bag, ipd);
5505         LINVRNT(osd_invariant(obj));
5506         osd_trans_exec_check(env, th, OSD_OT_INSERT);
5507         RETURN(rc);
5508 }
5509
5510 /**
5511  * Calls ldiskfs_add_entry() to add directory entry
5512  * into the directory. This is required for
5513  * interoperability mode (b11826)
5514  *
5515  * \retval   0, on success
5516  * \retval -ve, on error
5517  */
5518 static int __osd_ea_add_rec(struct osd_thread_info *info,
5519                             struct osd_object *pobj, struct inode  *cinode,
5520                             const char *name, const struct lu_fid *fid,
5521                             struct htree_lock *hlock, struct thandle *th)
5522 {
5523         struct ldiskfs_dentry_param *ldp;
5524         struct dentry *child;
5525         struct osd_thandle *oth;
5526         int rc;
5527
5528         oth = container_of(th, struct osd_thandle, ot_super);
5529         LASSERT(oth->ot_handle != NULL);
5530         LASSERT(oth->ot_handle->h_transaction != NULL);
5531         LASSERT(pobj->oo_inode);
5532
5533         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
5534         if (unlikely(pobj->oo_inode ==
5535                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
5536                 ldp->edp_magic = 0;
5537         else
5538                 osd_get_ldiskfs_dirent_param(ldp, fid);
5539         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
5540         child->d_fsdata = (void *)ldp;
5541         ll_vfs_dq_init(pobj->oo_inode);
5542         rc = osd_ldiskfs_add_entry(info, osd_obj2dev(pobj), oth->ot_handle,
5543                                    child, cinode, hlock);
5544         if (rc == 0 && OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_TYPE)) {
5545                 struct ldiskfs_dir_entry_2      *de;
5546                 struct buffer_head              *bh;
5547                 int                              rc1;
5548
5549                 bh = osd_ldiskfs_find_entry(pobj->oo_inode, &child->d_name, &de,
5550                                             NULL, hlock);
5551                 if (!IS_ERR(bh)) {
5552                         rc1 = ldiskfs_journal_get_write_access(oth->ot_handle,
5553                                                                bh);
5554                         if (rc1 == 0) {
5555                                 if (S_ISDIR(cinode->i_mode))
5556                                         de->file_type = LDISKFS_DIRENT_LUFID |
5557                                                         LDISKFS_FT_REG_FILE;
5558                                 else
5559                                         de->file_type = LDISKFS_DIRENT_LUFID |
5560                                                         LDISKFS_FT_DIR;
5561                                 ldiskfs_handle_dirty_metadata(oth->ot_handle,
5562                                                               NULL, bh);
5563                         }
5564                         brelse(bh);
5565                 }
5566         }
5567
5568         RETURN(rc);
5569 }
5570
5571 /**
5572  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
5573  * into the directory.Also sets flags into osd object to
5574  * indicate dot and dotdot are created. This is required for
5575  * interoperability mode (b11826)
5576  *
5577  * \param dir   directory for dot and dotdot fixup.
5578  * \param obj   child object for linking
5579  *
5580  * \retval   0, on success
5581  * \retval -ve, on error
5582  */
5583 static int osd_add_dot_dotdot(struct osd_thread_info *info,
5584                               struct osd_object *dir,
5585                               struct inode *parent_dir, const char *name,
5586                               const struct lu_fid *dot_fid,
5587                               const struct lu_fid *dot_dot_fid,
5588                               struct thandle *th)
5589 {
5590         struct inode *inode = dir->oo_inode;
5591         struct osd_thandle *oth;
5592         int result = 0;
5593
5594         oth = container_of(th, struct osd_thandle, ot_super);
5595         LASSERT(oth->ot_handle->h_transaction != NULL);
5596         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
5597
5598         if (strcmp(name, dot) == 0) {
5599                 if (dir->oo_compat_dot_created) {
5600                         result = -EEXIST;
5601                 } else {
5602                         LASSERT(inode->i_ino == parent_dir->i_ino);
5603                         dir->oo_compat_dot_created = 1;
5604                         result = 0;
5605                 }
5606         } else if (strcmp(name, dotdot) == 0) {
5607                 if (!dir->oo_compat_dot_created)
5608                         return -EINVAL;
5609                 /* in case of rename, dotdot is already created */
5610                 if (dir->oo_compat_dotdot_created) {
5611                         return __osd_ea_add_rec(info, dir, parent_dir, name,
5612                                                 dot_dot_fid, NULL, th);
5613                 }
5614
5615                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
5616                         struct lu_fid tfid = *dot_dot_fid;
5617
5618                         tfid.f_oid--;
5619                         result = osd_add_dot_dotdot_internal(info,
5620                                         dir->oo_inode, parent_dir, dot_fid,
5621                                         &tfid, oth);
5622                 } else {
5623                         result = osd_add_dot_dotdot_internal(info,
5624                                         dir->oo_inode, parent_dir, dot_fid,
5625                                         dot_dot_fid, oth);
5626                 }
5627
5628                 if (result == 0)
5629                         dir->oo_compat_dotdot_created = 1;
5630         }
5631
5632         return result;
5633 }
5634
5635
5636 /**
5637  * It will call the appropriate osd_add* function and return the
5638  * value, return by respective functions.
5639  */
5640 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
5641                           struct inode *cinode, const char *name,
5642                           const struct lu_fid *fid, struct thandle *th)
5643 {
5644         struct osd_thread_info *info = osd_oti_get(env);
5645         struct htree_lock *hlock;
5646         int rc;
5647
5648         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
5649
5650         if (name[0] == '.' && (name[1] == '\0' ||
5651                                (name[1] == '.' && name[2] == '\0'))) {
5652                 if (hlock != NULL) {
5653                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5654                                            pobj->oo_inode, 0);
5655                 } else {
5656                         down_write(&pobj->oo_ext_idx_sem);
5657                 }
5658
5659                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
5660                                         lu_object_fid(&pobj->oo_dt.do_lu),
5661                                         fid, th);
5662         } else {
5663                 if (hlock != NULL) {
5664                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5665                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
5666                 } else {
5667                         down_write(&pobj->oo_ext_idx_sem);
5668                 }
5669
5670                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
5671                         struct lu_fid *tfid = &info->oti_fid;
5672
5673                         *tfid = *fid;
5674                         tfid->f_ver = ~0;
5675                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
5676                                               tfid, hlock, th);
5677                 } else {
5678                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
5679                                               hlock, th);
5680                 }
5681         }
5682         if (hlock != NULL)
5683                 ldiskfs_htree_unlock(hlock);
5684         else
5685                 up_write(&pobj->oo_ext_idx_sem);
5686
5687         return rc;
5688 }
5689
5690 static int
5691 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
5692                       const struct lu_fid *fid, struct osd_inode_id *id)
5693 {
5694         struct lustre_scrub *scrub = &dev->od_scrub.os_scrub;
5695         struct inode *inode = NULL;
5696         int once = 0;
5697         bool insert;
5698         int rc;
5699
5700         ENTRY;
5701
5702         if (!fid_is_norm(fid) && !fid_is_igif(fid))
5703                 RETURN(0);
5704
5705         if (thread_is_running(&scrub->os_thread) &&
5706             scrub->os_pos_current > id->oii_ino)
5707                 RETURN(0);
5708
5709         if (dev->od_auto_scrub_interval == AS_NEVER ||
5710             ktime_get_real_seconds() <
5711             scrub->os_file.sf_time_last_complete + dev->od_auto_scrub_interval)
5712                 RETURN(0);
5713
5714 again:
5715         rc = osd_oi_lookup(oti, dev, fid, &oti->oti_id, 0);
5716         if (rc == -ENOENT) {
5717                 __u32 gen = id->oii_gen;
5718
5719                 insert = true;
5720                 if (inode != NULL)
5721                         goto trigger;
5722
5723                 inode = osd_iget(oti, dev, id);
5724                 /* The inode has been removed (by race maybe). */
5725                 if (IS_ERR(inode)) {
5726                         rc = PTR_ERR(inode);
5727
5728                         RETURN(rc == -ESTALE ? -ENOENT : rc);
5729                 }
5730
5731                 /* The OI mapping is lost. */
5732                 if (gen != OSD_OII_NOGEN)
5733                         goto trigger;
5734
5735                 /*
5736                  * The inode may has been reused by others, we do not know,
5737                  * leave it to be handled by subsequent osd_fid_lookup().
5738                  */
5739                 GOTO(out, rc = 0);
5740         } else if (rc || osd_id_eq(id, &oti->oti_id)) {
5741                 GOTO(out, rc);
5742         }
5743
5744         insert = false;
5745
5746 trigger:
5747         if (thread_is_running(&scrub->os_thread)) {
5748                 if (inode == NULL) {
5749                         inode = osd_iget(oti, dev, id);
5750                         /* The inode has been removed (by race maybe). */
5751                         if (IS_ERR(inode)) {
5752                                 rc = PTR_ERR(inode);
5753
5754                                 RETURN(rc == -ESTALE ? -ENOENT : rc);
5755                         }
5756                 }
5757
5758                 rc = osd_oii_insert(dev, fid, id, insert);
5759                 /*
5760                  * There is race condition between osd_oi_lookup and OI scrub.
5761                  * The OI scrub finished just after osd_oi_lookup() failure.
5762                  * Under such case, it is unnecessary to trigger OI scrub again,
5763                  * but try to call osd_oi_lookup() again.
5764                  */
5765                 if (unlikely(rc == -EAGAIN))
5766                         goto again;
5767
5768                 if (!S_ISDIR(inode->i_mode))
5769                         rc = 0;
5770                 else
5771                         rc = osd_check_lmv(oti, dev, inode);
5772
5773                 GOTO(out, rc);
5774         }
5775
5776         if (dev->od_auto_scrub_interval != AS_NEVER && ++once == 1) {
5777                 rc = osd_scrub_start(oti->oti_env, dev, SS_AUTO_PARTIAL |
5778                                      SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT);
5779                 CDEBUG(D_LFSCK | D_CONSOLE | D_WARNING,
5780                        "%s: trigger partial OI scrub for RPC inconsistency "
5781                        "checking FID "DFID": rc = %d\n",
5782                        osd_dev2name(dev), PFID(fid), rc);
5783                 if (rc == 0 || rc == -EALREADY)
5784                         goto again;
5785         }
5786
5787         GOTO(out, rc);
5788
5789 out:
5790         if (inode)
5791                 iput(inode);
5792
5793         RETURN(rc);
5794 }
5795
5796 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
5797                                struct osd_device *dev,
5798                                struct lu_fid *fid, __u32 ino)
5799 {
5800         struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
5801         struct osd_idmap_cache *oic = &oti->oti_cache;
5802         struct inode *inode;
5803         int rc;
5804
5805         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
5806         inode = osd_iget(oti, dev, &oic->oic_lid);
5807         if (IS_ERR(inode)) {
5808                 fid_zero(&oic->oic_fid);
5809                 return PTR_ERR(inode);
5810         }
5811
5812         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, loa);
5813         iput(inode);
5814         if (rc != 0)
5815                 fid_zero(&oic->oic_fid);
5816         else
5817                 *fid = oic->oic_fid = loa->loa_lma.lma_self_fid;
5818         return rc;
5819 }
5820
5821 void osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
5822                       struct osd_inode_id *id, const struct lu_fid *fid)
5823 {
5824         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
5825                id->oii_ino, id->oii_gen, info);
5826         info->oti_cache.oic_lid = *id;
5827         info->oti_cache.oic_fid = *fid;
5828         info->oti_cache.oic_dev = osd;
5829 }
5830
5831 /**
5832  * Get parent FID from the linkEA.
5833  *
5834  * For a directory which parent resides on remote MDT, to satisfy the
5835  * local e2fsck, we insert it into the /REMOTE_PARENT_DIR locally. On
5836  * the other hand, to make the lookup(..) on the directory can return
5837  * the real parent FID, we append the real parent FID after its ".."
5838  * name entry in the /REMOTE_PARENT_DIR.
5839  *
5840  * Unfortunately, such PFID-in-dirent cannot be preserved via file-level
5841  * backup. So after the restore, we cannot get the right parent FID from
5842  * its ".." name entry in the /REMOTE_PARENT_DIR. Under such case, since
5843  * we have stored the real parent FID in the directory object's linkEA,
5844  * we can parse the linkEA for the real parent FID.
5845  *
5846  * \param[in] env       pointer to the thread context
5847  * \param[in] obj       pointer to the object to be handled
5848  * \param[out]fid       pointer to the buffer to hold the parent FID
5849  *
5850  * \retval              0 for getting the real parent FID successfully
5851  * \retval              negative error number on failure
5852  */
5853 static int osd_get_pfid_from_linkea(const struct lu_env *env,
5854                                     struct osd_object *obj,
5855                                     struct lu_fid *fid)
5856 {
5857         struct osd_thread_info *oti = osd_oti_get(env);
5858         struct lu_buf *buf = &oti->oti_big_buf;
5859         struct dentry *dentry = &oti->oti_obj_dentry;
5860         struct inode *inode = obj->oo_inode;
5861         struct linkea_data ldata = { NULL };
5862         int rc;
5863
5864         ENTRY;
5865
5866         fid_zero(fid);
5867         if (!S_ISDIR(inode->i_mode))
5868                 RETURN(-EIO);
5869
5870 again:
5871         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5872                              buf->lb_buf, buf->lb_len);
5873         if (rc == -ERANGE) {
5874                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5875                                      NULL, 0);
5876                 if (rc > 0) {
5877                         lu_buf_realloc(buf, rc);
5878                         if (buf->lb_buf == NULL)
5879                                 RETURN(-ENOMEM);
5880
5881                         goto again;
5882                 }
5883         }
5884
5885         if (unlikely(rc == 0))
5886                 RETURN(-ENODATA);
5887
5888         if (rc < 0)
5889                 RETURN(rc);
5890
5891         if (unlikely(buf->lb_buf == NULL)) {
5892                 lu_buf_realloc(buf, rc);
5893                 if (buf->lb_buf == NULL)
5894                         RETURN(-ENOMEM);
5895
5896                 goto again;
5897         }
5898
5899         ldata.ld_buf = buf;
5900         rc = linkea_init_with_rec(&ldata);
5901         if (!rc) {
5902                 linkea_first_entry(&ldata);
5903                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, NULL, fid);
5904         }
5905
5906         RETURN(rc);
5907 }
5908
5909 static int osd_verify_ent_by_linkea(const struct lu_env *env,
5910                                     struct inode *inode,
5911                                     const struct lu_fid *pfid,
5912                                     const char *name, const int namelen)
5913 {
5914         struct osd_thread_info *oti = osd_oti_get(env);
5915         struct lu_buf *buf = &oti->oti_big_buf;
5916         struct dentry *dentry = &oti->oti_obj_dentry;
5917         struct linkea_data ldata = { NULL };
5918         struct lu_name cname = { .ln_name = name,
5919                                  .ln_namelen = namelen };
5920         int rc;
5921
5922         ENTRY;
5923
5924 again:
5925         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5926                              buf->lb_buf, buf->lb_len);
5927         if (rc == -ERANGE)
5928                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK, NULL, 0);
5929
5930         if (rc < 0)
5931                 RETURN(rc);
5932
5933         if (unlikely(rc == 0))
5934                 RETURN(-ENODATA);
5935
5936         if (buf->lb_len < rc) {
5937                 lu_buf_realloc(buf, rc);
5938                 if (buf->lb_buf == NULL)
5939                         RETURN(-ENOMEM);
5940
5941                 goto again;
5942         }
5943
5944         ldata.ld_buf = buf;
5945         rc = linkea_init_with_rec(&ldata);
5946         if (!rc)
5947                 rc = linkea_links_find(&ldata, &cname, pfid);
5948
5949         RETURN(rc);
5950 }
5951
5952 /**
5953  * Calls ->lookup() to find dentry. From dentry get inode and
5954  * read inode's ea to get fid. This is required for  interoperability
5955  * mode (b11826)
5956  *
5957  * \retval   0, on success
5958  * \retval -ve, on error
5959  */
5960 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
5961                              struct dt_rec *rec, const struct dt_key *key)
5962 {
5963         struct inode *dir = obj->oo_inode;
5964         struct dentry *dentry;
5965         struct ldiskfs_dir_entry_2 *de;
5966         struct buffer_head *bh;
5967         struct lu_fid *fid = (struct lu_fid *)rec;
5968         struct htree_lock *hlock = NULL;
5969         int ino;
5970         int rc;
5971
5972         ENTRY;
5973
5974         LASSERT(dir->i_op != NULL);
5975         LASSERT(dir->i_op->lookup != NULL);
5976
5977         dentry = osd_child_dentry_get(env, obj,
5978                                       (char *)key, strlen((char *)key));
5979
5980         if (obj->oo_hl_head != NULL) {
5981                 hlock = osd_oti_get(env)->oti_hlock;
5982                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5983                                    dir, LDISKFS_HLOCK_LOOKUP);
5984         } else {
5985                 down_read(&obj->oo_ext_idx_sem);
5986         }
5987
5988         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5989         if (!IS_ERR(bh)) {
5990                 struct osd_thread_info *oti = osd_oti_get(env);
5991                 struct osd_inode_id *id = &oti->oti_id;
5992                 struct osd_device *dev = osd_obj2dev(obj);
5993
5994                 ino = le32_to_cpu(de->inode);
5995                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
5996                         brelse(bh);
5997                         rc = osd_fail_fid_lookup(oti, dev, fid, ino);
5998                         GOTO(out, rc);
5999                 }
6000
6001                 rc = osd_get_fid_from_dentry(de, rec);
6002
6003                 /* done with de, release bh */
6004                 brelse(bh);
6005                 if (rc != 0) {
6006                         if (unlikely(is_remote_parent_ino(dev, ino))) {
6007                                 const char *name = (const char *)key;
6008
6009                                 /*
6010                                  * If the parent is on remote MDT, and there
6011                                  * is no FID-in-dirent, then we have to get
6012                                  * the parent FID from the linkEA.
6013                                  */
6014                                 if (likely(strlen(name) == 2 &&
6015                                            name[0] == '.' && name[1] == '.'))
6016                                         rc = osd_get_pfid_from_linkea(env, obj,
6017                                                                       fid);
6018                         } else {
6019                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
6020                         }
6021                 } else {
6022                         osd_id_gen(id, ino, OSD_OII_NOGEN);
6023                 }
6024
6025                 if (rc != 0 || osd_remote_fid(env, dev, fid))
6026                         GOTO(out, rc);
6027
6028                 rc = osd_consistency_check(oti, dev, fid, id);
6029                 if (rc != -ENOENT) {
6030                         /* Other error should not affect lookup result. */
6031                         rc = 0;
6032
6033                         /* Normal file mapping should be added into OI cache
6034                          * after FID in LMA check, but for local files like
6035                          * hsm_actions, their FIDs are not stored in OI files,
6036                          * see osd_initial_OI_scrub(), and here is the only
6037                          * place to load mapping into OI cache.
6038                          */
6039                         if (!fid_is_namespace_visible(fid))
6040                                 osd_add_oi_cache(osd_oti_get(env),
6041                                                  osd_obj2dev(obj), id, fid);
6042                 }
6043         } else {
6044                 rc = PTR_ERR(bh);
6045         }
6046
6047         GOTO(out, rc);
6048
6049 out:
6050         if (hlock != NULL)
6051                 ldiskfs_htree_unlock(hlock);
6052         else
6053                 up_read(&obj->oo_ext_idx_sem);
6054         return rc;
6055 }
6056
6057 static int osd_index_declare_ea_insert(const struct lu_env *env,
6058                                        struct dt_object *dt,
6059                                        const struct dt_rec *rec,
6060                                        const struct dt_key *key,
6061                                        struct thandle *handle)
6062 {
6063         struct osd_thandle *oh;
6064         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
6065         struct dt_insert_rec *rec1 = (struct dt_insert_rec *)rec;
6066         const struct lu_fid *fid = rec1->rec_fid;
6067         int credits, rc = 0;
6068         struct osd_idmap_cache *idc;
6069
6070         ENTRY;
6071
6072         LASSERT(!dt_object_remote(dt));
6073         LASSERT(handle != NULL);
6074         LASSERT(fid != NULL);
6075         LASSERT(rec1->rec_type != 0);
6076
6077         oh = container_of0(handle, struct osd_thandle, ot_super);
6078         LASSERT(oh->ot_handle == NULL);
6079
6080         credits = osd_dto_credits_noquota[DTO_INDEX_INSERT];
6081
6082         /*
6083          * we can't call iget() while a transactions is running
6084          * (this can lead to a deadlock), but we need to know
6085          * inum and object type. so we find this information at
6086          * declaration and cache in per-thread info
6087          */
6088         idc = osd_idc_find_or_init(env, osd, fid);
6089         if (IS_ERR(idc))
6090                 RETURN(PTR_ERR(idc));
6091         if (idc->oic_remote) {
6092                 /*
6093                  * a reference to remote inode is represented by an
6094                  * agent inode which we have to create
6095                  */
6096                 credits += osd_dto_credits_noquota[DTO_OBJECT_CREATE];
6097                 credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
6098         }
6099
6100         osd_trans_declare_op(env, oh, OSD_OT_INSERT, credits);
6101
6102         if (osd_dt_obj(dt)->oo_inode != NULL) {
6103                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
6104
6105                 /*
6106                  * We ignore block quota on meta pool (MDTs), so needn't
6107                  * calculate how many blocks will be consumed by this index
6108                  * insert
6109                  */
6110                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
6111                                            i_gid_read(inode),
6112                                            i_projid_read(inode), 0,
6113                                            oh, osd_dt_obj(dt), NULL,
6114                                            OSD_QID_BLK);
6115                 if (rc)
6116                         RETURN(rc);
6117
6118 #ifdef HAVE_PROJECT_QUOTA
6119                 /*
6120                  * Reserve credits for local agent inode to transfer
6121                  * to 0, quota enforcement is ignored in this case.
6122                  */
6123                 if (idc->oic_remote &&
6124                     LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
6125                     i_projid_read(inode) != 0)
6126                         rc = osd_declare_attr_qid(env, osd_dt_obj(dt), oh,
6127                                                   0, i_projid_read(inode),
6128                                                   0, false, PRJQUOTA, true);
6129 #endif
6130         }
6131
6132         RETURN(rc);
6133 }
6134
6135 /**
6136  * Index add function for interoperability mode (b11826).
6137  * It will add the directory entry.This entry is needed to
6138  * maintain name->fid mapping.
6139  *
6140  * \param key it is key i.e. file entry to be inserted
6141  * \param rec it is value of given key i.e. fid
6142  *
6143  * \retval   0, on success
6144  * \retval -ve, on error
6145  */
6146 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
6147                                const struct dt_rec *rec,
6148                                const struct dt_key *key, struct thandle *th)
6149 {
6150         struct osd_object *obj = osd_dt_obj(dt);
6151         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
6152         struct dt_insert_rec *rec1 = (struct dt_insert_rec *)rec;
6153         const struct lu_fid *fid = rec1->rec_fid;
6154         const char *name = (const char *)key;
6155         struct osd_thread_info *oti = osd_oti_get(env);
6156         struct inode *child_inode = NULL;
6157         struct osd_idmap_cache *idc;
6158         int rc;
6159
6160         ENTRY;
6161
6162         if (!dt_object_exists(dt))
6163                 RETURN(-ENOENT);
6164
6165         LASSERT(osd_invariant(obj));
6166         LASSERT(!dt_object_remote(dt));
6167         LASSERT(th != NULL);
6168
6169         osd_trans_exec_op(env, th, OSD_OT_INSERT);
6170
6171         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!\n", PFID(fid));
6172
6173         idc = osd_idc_find(env, osd, fid);
6174         if (unlikely(idc == NULL)) {
6175                 idc = osd_idc_find_or_init(env, osd, fid);
6176                 if (IS_ERR(idc)) {
6177                         /*
6178                          * this dt_insert() wasn't declared properly, so
6179                          * FID is missing in OI cache. we better do not
6180                          * lookup FID in FLDB/OI and don't risk to deadlock,
6181                          * but in some special cases (lfsck testing, etc)
6182                          * it's much simpler than fixing a caller.
6183                          *
6184                          * normally this error should be placed after the first
6185                          * find, but migrate may attach source stripes to
6186                          * target, which doesn't create stripes.
6187                          */
6188                         CERROR("%s: "DFID" wasn't declared for insert\n",
6189                                osd_name(osd), PFID(fid));
6190                         dump_stack();
6191                         RETURN(PTR_ERR(idc));
6192                 }
6193         }
6194
6195         if (idc->oic_remote) {
6196                 /* Insert remote entry */
6197                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
6198                         child_inode =
6199                         igrab(osd->od_mdt_map->omm_remote_parent->d_inode);
6200                 } else {
6201                         child_inode = osd_create_local_agent_inode(env, osd,
6202                                         obj, fid, rec1->rec_type & S_IFMT, th);
6203                         if (IS_ERR(child_inode))
6204                                 RETURN(PTR_ERR(child_inode));
6205                 }
6206         } else {
6207                 /* Insert local entry */
6208                 if (unlikely(idc->oic_lid.oii_ino == 0)) {
6209                         /* for a reason OI cache wasn't filled properly */
6210                         CERROR("%s: OIC for "DFID" isn't filled\n",
6211                                osd_name(osd), PFID(fid));
6212                         RETURN(-EINVAL);
6213                 }
6214                 child_inode = oti->oti_inode;
6215                 if (unlikely(child_inode == NULL)) {
6216                         struct ldiskfs_inode_info *lii;
6217
6218                         OBD_ALLOC_PTR(lii);
6219                         if (lii == NULL)
6220                                 RETURN(-ENOMEM);
6221                         child_inode = oti->oti_inode = &lii->vfs_inode;
6222                 }
6223                 child_inode->i_sb = osd_sb(osd);
6224                 child_inode->i_ino = idc->oic_lid.oii_ino;
6225                 child_inode->i_mode = rec1->rec_type & S_IFMT;
6226         }
6227
6228         rc = osd_ea_add_rec(env, obj, child_inode, name, fid, th);
6229
6230         CDEBUG(D_INODE, "parent %lu insert %s:%lu rc = %d\n",
6231                obj->oo_inode->i_ino, name, child_inode->i_ino, rc);
6232
6233         if (child_inode && child_inode != oti->oti_inode)
6234                 iput(child_inode);
6235         LASSERT(osd_invariant(obj));
6236         osd_trans_exec_check(env, th, OSD_OT_INSERT);
6237         RETURN(rc);
6238 }
6239
6240 /**
6241  *  Initialize osd Iterator for given osd index object.
6242  *
6243  *  \param  dt      osd index object
6244  */
6245
6246 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
6247                                      struct dt_object *dt,
6248                                      __u32 unused)
6249 {
6250         struct osd_it_iam *it;
6251         struct osd_object *obj = osd_dt_obj(dt);
6252         struct lu_object *lo = &dt->do_lu;
6253         struct iam_path_descr *ipd;
6254         struct iam_container *bag = &obj->oo_dir->od_container;
6255
6256         if (!dt_object_exists(dt))
6257                 return ERR_PTR(-ENOENT);
6258
6259         OBD_ALLOC_PTR(it);
6260         if (it == NULL)
6261                 return ERR_PTR(-ENOMEM);
6262
6263         ipd = osd_it_ipd_get(env, bag);
6264         if (likely(ipd != NULL)) {
6265                 it->oi_obj = obj;
6266                 it->oi_ipd = ipd;
6267                 lu_object_get(lo);
6268                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
6269                 return (struct dt_it *)it;
6270         } else {
6271                 OBD_FREE_PTR(it);
6272                 return ERR_PTR(-ENOMEM);
6273         }
6274 }
6275
6276 /**
6277  * free given Iterator.
6278  */
6279 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
6280 {
6281         struct osd_it_iam *it  = (struct osd_it_iam *)di;
6282         struct osd_object *obj = it->oi_obj;
6283
6284         iam_it_fini(&it->oi_it);
6285         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
6286         osd_object_put(env, obj);
6287         OBD_FREE_PTR(it);
6288 }
6289
6290 /**
6291  *  Move Iterator to record specified by \a key
6292  *
6293  *  \param  di      osd iterator
6294  *  \param  key     key for index
6295  *
6296  *  \retval +ve  di points to record with least key not larger than key
6297  *  \retval  0   di points to exact matched key
6298  *  \retval -ve  failure
6299  */
6300
6301 static int osd_it_iam_get(const struct lu_env *env,
6302                           struct dt_it *di, const struct dt_key *key)
6303 {
6304         struct osd_thread_info *oti = osd_oti_get(env);
6305         struct osd_it_iam *it = (struct osd_it_iam *)di;
6306
6307         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
6308                 /* swab quota uid/gid */
6309                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
6310                 key = (struct dt_key *)&oti->oti_quota_id;
6311         }
6312
6313         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
6314 }
6315
6316 /**
6317  *  Release Iterator
6318  *
6319  *  \param  di      osd iterator
6320  */
6321 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
6322 {
6323         struct osd_it_iam *it = (struct osd_it_iam *)di;
6324
6325         iam_it_put(&it->oi_it);
6326 }
6327
6328 /**
6329  *  Move iterator by one record
6330  *
6331  *  \param  di      osd iterator
6332  *
6333  *  \retval +1   end of container reached
6334  *  \retval  0   success
6335  *  \retval -ve  failure
6336  */
6337
6338 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
6339 {
6340         struct osd_it_iam *it = (struct osd_it_iam *)di;
6341
6342         return iam_it_next(&it->oi_it);
6343 }
6344
6345 /**
6346  * Return pointer to the key under iterator.
6347  */
6348
6349 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
6350                                      const struct dt_it *di)
6351 {
6352         struct osd_thread_info *oti = osd_oti_get(env);
6353         struct osd_it_iam *it = (struct osd_it_iam *)di;
6354         struct osd_object *obj = it->oi_obj;
6355         struct dt_key *key;
6356
6357         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
6358
6359         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
6360                 /* swab quota uid/gid */
6361                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
6362                 key = (struct dt_key *)&oti->oti_quota_id;
6363         }
6364
6365         return key;
6366 }
6367
6368 /**
6369  * Return size of key under iterator (in bytes)
6370  */
6371
6372 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
6373 {
6374         struct osd_it_iam *it = (struct osd_it_iam *)di;
6375
6376         return iam_it_key_size(&it->oi_it);
6377 }
6378
6379 static inline void
6380 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
6381 {
6382         /* check if file type is required */
6383         if (ent->lde_attrs & LUDA_TYPE) {
6384                 struct luda_type *lt;
6385                 int align = sizeof(*lt) - 1;
6386
6387                 len = (len + align) & ~align;
6388                 lt = (struct luda_type *)(ent->lde_name + len);
6389                 lt->lt_type = cpu_to_le16(DTTOIF(type));
6390         }
6391
6392         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
6393 }
6394
6395 /**
6396  * build lu direct from backend fs dirent.
6397  */
6398
6399 static inline void
6400 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
6401                    char *name, __u16 namelen, __u16 type, __u32 attr)
6402 {
6403         ent->lde_attrs = attr | LUDA_FID;
6404         fid_cpu_to_le(&ent->lde_fid, fid);
6405
6406         ent->lde_hash = cpu_to_le64(offset);
6407         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
6408
6409         strncpy(ent->lde_name, name, namelen);
6410         ent->lde_name[namelen] = '\0';
6411         ent->lde_namelen = cpu_to_le16(namelen);
6412
6413         /* append lustre attributes */
6414         osd_it_append_attrs(ent, namelen, type);
6415 }
6416
6417 /**
6418  * Return pointer to the record under iterator.
6419  */
6420 static int osd_it_iam_rec(const struct lu_env *env,
6421                           const struct dt_it *di,
6422                           struct dt_rec *dtrec, __u32 attr)
6423 {
6424         struct osd_it_iam *it = (struct osd_it_iam *)di;
6425         struct osd_thread_info *info = osd_oti_get(env);
6426
6427         ENTRY;
6428
6429         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
6430                 const struct osd_fid_pack *rec;
6431                 struct lu_fid *fid = &info->oti_fid;
6432                 struct lu_dirent *lde = (struct lu_dirent *)dtrec;
6433                 char *name;
6434                 int namelen;
6435                 __u64 hash;
6436                 int rc;
6437
6438                 name = (char *)iam_it_key_get(&it->oi_it);
6439                 if (IS_ERR(name))
6440                         RETURN(PTR_ERR(name));
6441
6442                 namelen = iam_it_key_size(&it->oi_it);
6443
6444                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
6445                 if (IS_ERR(rec))
6446                         RETURN(PTR_ERR(rec));
6447
6448                 rc = osd_fid_unpack(fid, rec);
6449                 if (rc)
6450                         RETURN(rc);
6451
6452                 hash = iam_it_store(&it->oi_it);
6453
6454                 /* IAM does not store object type in IAM index (dir) */
6455                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
6456                                    0, LUDA_FID);
6457         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
6458                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
6459                            (struct iam_rec *)dtrec);
6460                 osd_quota_unpack(it->oi_obj, dtrec);
6461         } else {
6462                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
6463                            (struct iam_rec *)dtrec);
6464         }
6465
6466         RETURN(0);
6467 }
6468
6469 /**
6470  * Returns cookie for current Iterator position.
6471  */
6472 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
6473 {
6474         struct osd_it_iam *it = (struct osd_it_iam *)di;
6475
6476         return iam_it_store(&it->oi_it);
6477 }
6478
6479 /**
6480  * Restore iterator from cookie.
6481  *
6482  * \param  di      osd iterator
6483  * \param  hash    Iterator location cookie
6484  *
6485  * \retval +ve  di points to record with least key not larger than key.
6486  * \retval  0   di points to exact matched key
6487  * \retval -ve  failure
6488  */
6489
6490 static int osd_it_iam_load(const struct lu_env *env,
6491                            const struct dt_it *di, __u64 hash)
6492 {
6493         struct osd_it_iam *it = (struct osd_it_iam *)di;
6494
6495         return iam_it_load(&it->oi_it, hash);
6496 }
6497
6498 static const struct dt_index_operations osd_index_iam_ops = {
6499         .dio_lookup         = osd_index_iam_lookup,
6500         .dio_declare_insert = osd_index_declare_iam_insert,
6501         .dio_insert         = osd_index_iam_insert,
6502         .dio_declare_delete = osd_index_declare_iam_delete,
6503         .dio_delete         = osd_index_iam_delete,
6504         .dio_it     = {
6505                 .init     = osd_it_iam_init,
6506                 .fini     = osd_it_iam_fini,
6507                 .get      = osd_it_iam_get,
6508                 .put      = osd_it_iam_put,
6509                 .next     = osd_it_iam_next,
6510                 .key      = osd_it_iam_key,
6511                 .key_size = osd_it_iam_key_size,
6512                 .rec      = osd_it_iam_rec,
6513                 .store    = osd_it_iam_store,
6514                 .load     = osd_it_iam_load
6515         }
6516 };
6517
6518
6519 /**
6520  * Creates or initializes iterator context.
6521  *
6522  * \retval struct osd_it_ea, iterator structure on success
6523  *
6524  */
6525 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
6526                                     struct dt_object *dt,
6527                                     __u32 attr)
6528 {
6529         struct osd_object *obj = osd_dt_obj(dt);
6530         struct osd_thread_info *info = osd_oti_get(env);
6531         struct osd_it_ea *oie;
6532         struct file *file;
6533         struct lu_object *lo = &dt->do_lu;
6534         struct dentry *obj_dentry;
6535
6536         ENTRY;
6537
6538         if (!dt_object_exists(dt) || obj->oo_destroyed)
6539                 RETURN(ERR_PTR(-ENOENT));
6540
6541         OBD_SLAB_ALLOC_PTR_GFP(oie, osd_itea_cachep, GFP_NOFS);
6542         if (oie == NULL)
6543                 RETURN(ERR_PTR(-ENOMEM));
6544         obj_dentry = &oie->oie_dentry;
6545
6546         obj_dentry->d_inode = obj->oo_inode;
6547         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
6548         obj_dentry->d_name.hash = 0;
6549
6550         oie->oie_rd_dirent       = 0;
6551         oie->oie_it_dirent       = 0;
6552         oie->oie_dirent          = NULL;
6553         if (unlikely(!info->oti_it_ea_buf_used)) {
6554                 oie->oie_buf = info->oti_it_ea_buf;
6555                 info->oti_it_ea_buf_used = 1;
6556         } else {
6557                 OBD_ALLOC(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6558                 if (oie->oie_buf == NULL)
6559                         RETURN(ERR_PTR(-ENOMEM));
6560         }
6561         oie->oie_obj = obj;
6562
6563         file = &oie->oie_file;
6564
6565         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
6566         if (attr & LUDA_64BITHASH)
6567                 file->f_mode    = FMODE_64BITHASH;
6568         else
6569                 file->f_mode    = FMODE_32BITHASH;
6570         file->f_path.dentry     = obj_dentry;
6571         file->f_mapping         = obj->oo_inode->i_mapping;
6572         file->f_op              = obj->oo_inode->i_fop;
6573         set_file_inode(file, obj->oo_inode);
6574
6575         lu_object_get(lo);
6576         RETURN((struct dt_it *)oie);
6577 }
6578
6579 /**
6580  * Destroy or finishes iterator context.
6581  *
6582  * \param di iterator structure to be destroyed
6583  */
6584 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
6585 {
6586         struct osd_thread_info *info = osd_oti_get(env);
6587         struct osd_it_ea *oie = (struct osd_it_ea *)di;
6588         struct osd_object *obj = oie->oie_obj;
6589         struct inode *inode = obj->oo_inode;
6590
6591         ENTRY;
6592         oie->oie_file.f_op->release(inode, &oie->oie_file);
6593         osd_object_put(env, obj);
6594         if (unlikely(oie->oie_buf != info->oti_it_ea_buf))
6595                 OBD_FREE(oie->oie_buf, OSD_IT_EA_BUFSIZE);
6596         else
6597                 info->oti_it_ea_buf_used = 0;
6598         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
6599         EXIT;
6600 }
6601
6602 /**
6603  * It position the iterator at given key, so that next lookup continues from
6604  * that key Or it is similar to dio_it->load() but based on a key,
6605  * rather than file position.
6606  *
6607  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
6608  * to the beginning.
6609  *
6610  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
6611  */
6612 static int osd_it_ea_get(const struct lu_env *env,
6613                          struct dt_it *di, const struct dt_key *key)
6614 {
6615         struct osd_it_ea *it = (struct osd_it_ea *)di;
6616
6617         ENTRY;
6618         LASSERT(((const char *)key)[0] == '\0');
6619         it->oie_file.f_pos = 0;
6620         it->oie_rd_dirent = 0;
6621         it->oie_it_dirent = 0;
6622         it->oie_dirent = NULL;
6623
6624         RETURN(+1);
6625 }
6626
6627 /**
6628  * Does nothing
6629  */
6630 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
6631 {
6632 }
6633
6634 struct osd_filldir_cbs {
6635 #ifdef HAVE_DIR_CONTEXT
6636         struct dir_context ctx;
6637 #endif
6638         struct osd_it_ea  *it;
6639 };
6640 /**
6641  * It is called internally by ->readdir(). It fills the
6642  * iterator's in-memory data structure with required
6643  * information i.e. name, namelen, rec_size etc.
6644  *
6645  * \param buf in which information to be filled in.
6646  * \param name name of the file in given dir
6647  *
6648  * \retval 0 on success
6649  * \retval 1 on buffer full
6650  */
6651 #ifdef HAVE_FILLDIR_USE_CTX
6652 static int osd_ldiskfs_filldir(struct dir_context *buf,
6653 #else
6654 static int osd_ldiskfs_filldir(void *buf,
6655 #endif
6656                                const char *name, int namelen,
6657                                loff_t offset, __u64 ino, unsigned int d_type)
6658 {
6659         struct osd_it_ea *it = ((struct osd_filldir_cbs *)buf)->it;
6660         struct osd_object *obj = it->oie_obj;
6661         struct osd_it_ea_dirent *ent = it->oie_dirent;
6662         struct lu_fid *fid = &ent->oied_fid;
6663         struct osd_fid_pack *rec;
6664
6665         ENTRY;
6666
6667 /* this should never happen */
6668         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
6669                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
6670                 RETURN(-EIO);
6671         }
6672
6673         if ((void *)ent - it->oie_buf + sizeof(*ent) + namelen >
6674             OSD_IT_EA_BUFSIZE)
6675                 RETURN(1);
6676
6677         /* "." is just the object itself. */
6678         if (namelen == 1 && name[0] == '.') {
6679                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
6680         } else if (d_type & LDISKFS_DIRENT_LUFID) {
6681                 rec = (struct osd_fid_pack *)(name + namelen + 1);
6682                 if (osd_fid_unpack(fid, rec) != 0)
6683                         fid_zero(fid);
6684         } else {
6685                 fid_zero(fid);
6686         }
6687         d_type &= ~LDISKFS_DIRENT_LUFID;
6688
6689         /* NOT export local root. */
6690         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
6691                 ino = obj->oo_inode->i_ino;
6692                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
6693         }
6694
6695         ent->oied_ino     = ino;
6696         ent->oied_off     = offset;
6697         ent->oied_namelen = namelen;
6698         ent->oied_type    = d_type;
6699
6700         memcpy(ent->oied_name, name, namelen);
6701
6702         it->oie_rd_dirent++;
6703         it->oie_dirent = (void *)ent + cfs_size_round(sizeof(*ent) + namelen);
6704         RETURN(0);
6705 }
6706
6707 /**
6708  * Calls ->readdir() to load a directory entry at a time
6709  * and stored it in iterator's in-memory data structure.
6710  *
6711  * \param di iterator's in memory structure
6712  *
6713  * \retval   0 on success
6714  * \retval -ve on error
6715  * \retval +1 reach the end of entry
6716  */
6717 static int osd_ldiskfs_it_fill(const struct lu_env *env,
6718                                const struct dt_it *di)
6719 {
6720         struct osd_it_ea *it = (struct osd_it_ea *)di;
6721         struct osd_object *obj = it->oie_obj;
6722         struct inode *inode = obj->oo_inode;
6723         struct htree_lock *hlock = NULL;
6724         struct file *filp = &it->oie_file;
6725         int rc = 0;
6726         struct osd_filldir_cbs buf = {
6727 #ifdef HAVE_DIR_CONTEXT
6728                 .ctx.actor = osd_ldiskfs_filldir,
6729 #endif
6730                 .it = it
6731         };
6732
6733         ENTRY;
6734         it->oie_dirent = it->oie_buf;
6735         it->oie_rd_dirent = 0;
6736
6737         if (obj->oo_hl_head != NULL) {
6738                 hlock = osd_oti_get(env)->oti_hlock;
6739                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
6740                                    inode, LDISKFS_HLOCK_READDIR);
6741         } else {
6742                 down_read(&obj->oo_ext_idx_sem);
6743         }
6744
6745 #ifdef HAVE_DIR_CONTEXT
6746         buf.ctx.pos = filp->f_pos;
6747 #ifdef HAVE_ITERATE_SHARED
6748         rc = inode->i_fop->iterate_shared(filp, &buf.ctx);
6749 #else
6750         rc = inode->i_fop->iterate(filp, &buf.ctx);
6751 #endif
6752         filp->f_pos = buf.ctx.pos;
6753 #else
6754         rc = inode->i_fop->readdir(filp, &buf, osd_ldiskfs_filldir);
6755 #endif
6756
6757         if (hlock != NULL)
6758                 ldiskfs_htree_unlock(hlock);
6759         else
6760                 up_read(&obj->oo_ext_idx_sem);
6761
6762         if (it->oie_rd_dirent == 0) {
6763                 /*
6764                  * If it does not get any dirent, it means it has been reached
6765                  * to the end of the dir
6766                  */
6767                 it->oie_file.f_pos = ldiskfs_get_htree_eof(&it->oie_file);
6768                 if (rc == 0)
6769                         rc = 1;
6770         } else {
6771                 it->oie_dirent = it->oie_buf;
6772                 it->oie_it_dirent = 1;
6773         }
6774
6775         RETURN(rc);
6776 }
6777
6778 /**
6779  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
6780  * to load a directory entry at a time and stored it in
6781  * iterator's in-memory data structure.
6782  *
6783  * \param di iterator's in memory structure
6784  *
6785  * \retval +ve iterator reached to end
6786  * \retval   0 iterator not reached to end
6787  * \retval -ve on error
6788  */
6789 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
6790 {
6791         struct osd_it_ea *it = (struct osd_it_ea *)di;
6792         int rc;
6793
6794         ENTRY;
6795
6796         if (it->oie_it_dirent < it->oie_rd_dirent) {
6797                 it->oie_dirent =
6798                         (void *)it->oie_dirent +
6799                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
6800                                        it->oie_dirent->oied_namelen);
6801                 it->oie_it_dirent++;
6802                 rc = 0;
6803         } else {
6804                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
6805                         rc = 1;
6806                 else
6807                         rc = osd_ldiskfs_it_fill(env, di);
6808         }
6809
6810         RETURN(rc);
6811 }
6812
6813 /**
6814  * Returns the key at current position from iterator's in memory structure.
6815  *
6816  * \param di iterator's in memory structure
6817  *
6818  * \retval key i.e. struct dt_key on success
6819  */
6820 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
6821                                     const struct dt_it *di)
6822 {
6823         struct osd_it_ea *it = (struct osd_it_ea *)di;
6824
6825         return (struct dt_key *)it->oie_dirent->oied_name;
6826 }
6827
6828 /**
6829  * Returns key's size at current position from iterator's in memory structure.
6830  *
6831  * \param di iterator's in memory structure
6832  *
6833  * \retval key_size i.e. struct dt_key on success
6834  */
6835 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
6836 {
6837         struct osd_it_ea *it = (struct osd_it_ea *)di;
6838
6839         return it->oie_dirent->oied_namelen;
6840 }
6841
6842 static inline bool osd_dotdot_has_space(struct ldiskfs_dir_entry_2 *de)
6843 {
6844         if (LDISKFS_DIR_REC_LEN(de) >=
6845             __LDISKFS_DIR_REC_LEN(2 + 1 + sizeof(struct osd_fid_pack)))
6846                 return true;
6847
6848         return false;
6849 }
6850
6851 static inline bool
6852 osd_dirent_has_space(struct ldiskfs_dir_entry_2 *de, __u16 namelen,
6853                      unsigned int blocksize, bool dotdot)
6854 {
6855         if (dotdot)
6856                 return osd_dotdot_has_space(de);
6857
6858         if (ldiskfs_rec_len_from_disk(de->rec_len, blocksize) >=
6859             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
6860                 return true;
6861
6862         return false;
6863 }
6864
6865 static int
6866 osd_dirent_reinsert(const struct lu_env *env, struct osd_device *dev,
6867                     handle_t *jh, struct dentry *dentry,
6868                     const struct lu_fid *fid, struct buffer_head *bh,
6869                     struct ldiskfs_dir_entry_2 *de, struct htree_lock *hlock,
6870                     bool dotdot)
6871 {
6872         struct inode *dir = dentry->d_parent->d_inode;
6873         struct inode *inode = dentry->d_inode;
6874         struct osd_fid_pack *rec;
6875         struct ldiskfs_dentry_param *ldp;
6876         int namelen = dentry->d_name.len;
6877         int rc;
6878         struct osd_thread_info *info = osd_oti_get(env);
6879
6880         ENTRY;
6881
6882         if (!ldiskfs_has_feature_dirdata(inode->i_sb))
6883                 RETURN(0);
6884
6885         /* There is enough space to hold the FID-in-dirent. */
6886         if (osd_dirent_has_space(de, namelen, dir->i_sb->s_blocksize, dotdot)) {
6887                 rc = ldiskfs_journal_get_write_access(jh, bh);
6888                 if (rc != 0)
6889                         RETURN(rc);
6890
6891                 de->name[namelen] = 0;
6892                 rec = (struct osd_fid_pack *)(de->name + namelen + 1);
6893                 rec->fp_len = sizeof(struct lu_fid) + 1;
6894                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
6895                 de->file_type |= LDISKFS_DIRENT_LUFID;
6896                 rc = ldiskfs_handle_dirty_metadata(jh, NULL, bh);
6897
6898                 RETURN(rc);
6899         }
6900
6901         LASSERT(!dotdot);
6902
6903         rc = ldiskfs_delete_entry(jh, dir, de, bh);
6904         if (rc != 0)
6905                 RETURN(rc);
6906
6907         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
6908         osd_get_ldiskfs_dirent_param(ldp, fid);
6909         dentry->d_fsdata = (void *)ldp;
6910         ll_vfs_dq_init(dir);
6911         rc = osd_ldiskfs_add_entry(info, dev, jh, dentry, inode, hlock);
6912         /*
6913          * It is too bad, we cannot reinsert the name entry back.
6914          * That means we lose it!
6915          */
6916         if (rc != 0)
6917                 CDEBUG(D_LFSCK, "%s: fail to reinsert the dirent, "
6918                        "dir = %lu/%u, name = %.*s, "DFID": rc = %d\n",
6919                        osd_ino2name(inode),
6920                        dir->i_ino, dir->i_generation, namelen,
6921                        dentry->d_name.name, PFID(fid), rc);
6922
6923         RETURN(rc);
6924 }
6925
6926 static int
6927 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
6928                         struct osd_it_ea *it, struct lu_fid *fid,
6929                         struct osd_inode_id *id, __u32 *attr)
6930 {
6931         struct osd_thread_info *info = osd_oti_get(env);
6932         struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
6933         struct osd_device *dev = osd_obj2dev(obj);
6934         struct super_block *sb = osd_sb(dev);
6935         const char *devname = osd_name(dev);
6936         struct osd_it_ea_dirent *ent = it->oie_dirent;
6937         struct inode *dir = obj->oo_inode;
6938         struct htree_lock *hlock = NULL;
6939         struct buffer_head *bh = NULL;
6940         handle_t *jh = NULL;
6941         struct ldiskfs_dir_entry_2 *de;
6942         struct dentry *dentry;
6943         struct inode *inode;
6944         const struct lu_fid *pfid = lu_object_fid(&obj->oo_dt.do_lu);
6945         int credits;
6946         int rc;
6947         bool dotdot = false;
6948         bool dirty = false;
6949
6950         ENTRY;
6951
6952         if (ent->oied_name[0] == '.') {
6953                 if (ent->oied_namelen == 1)
6954                         RETURN(0);
6955
6956                 if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
6957                         dotdot = true;
6958         }
6959
6960         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
6961         inode = osd_iget(info, dev, id);
6962         if (IS_ERR(inode)) {
6963                 rc = PTR_ERR(inode);
6964                 if (rc == -ENOENT || rc == -ESTALE) {
6965                         /*
6966                          * Maybe dangling name entry, or
6967                          * corrupted directory entry.
6968                          */
6969                         *attr |= LUDA_UNKNOWN;
6970                         rc = 0;
6971                 } else {
6972                         CDEBUG(D_LFSCK, "%s: fail to iget() for dirent "
6973                                "check_repair, dir = %lu/%u, name = %.*s, "
6974                                "ino = %llu, rc = %d\n",
6975                                devname, dir->i_ino, dir->i_generation,
6976                                ent->oied_namelen, ent->oied_name,
6977                                ent->oied_ino, rc);
6978                 }
6979
6980                 RETURN(rc);
6981         }
6982
6983         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
6984                                            ent->oied_namelen);
6985         rc = osd_get_lma(info, inode, dentry, &info->oti_ost_attrs);
6986         if (rc == -ENODATA || !fid_is_sane(&lma->lma_self_fid))
6987                 lma = NULL;
6988         else if (rc != 0)
6989                 GOTO(out, rc);
6990
6991         /*
6992          * We need to ensure that the name entry is still valid.
6993          * Because it may be removed or renamed by other already.
6994          *
6995          * The unlink or rename operation will start journal before PDO lock,
6996          * so to avoid deadlock, here we need to start journal handle before
6997          * related PDO lock also. But because we do not know whether there
6998          * will be something to be repaired before PDO lock, we just start
6999          * journal without conditions.
7000          *
7001          * We may need to remove the name entry firstly, then insert back.
7002          * One credit is for user quota file update.
7003          * One credit is for group quota file update.
7004          * Two credits are for dirty inode.
7005          */
7006         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
7007                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
7008
7009         if (dev->od_dirent_journal != 0) {
7010
7011 again:
7012                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
7013                 if (IS_ERR(jh)) {
7014                         rc = PTR_ERR(jh);
7015                         CDEBUG(D_LFSCK, "%s: fail to start trans for dirent "
7016                                "check_repair, dir = %lu/%u, credits = %d, "
7017                                "name = %.*s, ino = %llu: rc = %d\n",
7018                                devname, dir->i_ino, dir->i_generation, credits,
7019                                ent->oied_namelen, ent->oied_name,
7020                                ent->oied_ino, rc);
7021
7022                         GOTO(out_inode, rc);
7023                 }
7024
7025                 if (obj->oo_hl_head != NULL) {
7026                         hlock = osd_oti_get(env)->oti_hlock;
7027                         /*
7028                          * "0" means exclusive lock for the whole directory.
7029                          * We need to prevent others access such name entry
7030                          * during the delete + insert. Neither HLOCK_ADD nor
7031                          * HLOCK_DEL cannot guarantee the atomicity.
7032                          */
7033                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
7034                 } else {
7035                         down_write(&obj->oo_ext_idx_sem);
7036                 }
7037         } else {
7038                 if (obj->oo_hl_head != NULL) {
7039                         hlock = osd_oti_get(env)->oti_hlock;
7040                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
7041                                            LDISKFS_HLOCK_LOOKUP);
7042                 } else {
7043                         down_read(&obj->oo_ext_idx_sem);
7044                 }
7045         }
7046
7047         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
7048         if (IS_ERR(bh) || le32_to_cpu(de->inode) != inode->i_ino) {
7049                 *attr |= LUDA_IGNORE;
7050
7051                 GOTO(out, rc = 0);
7052         }
7053
7054         /*
7055          * For dotdot entry, if there is not enough space to hold the
7056          * FID-in-dirent, just keep them there. It only happens when the
7057          * device upgraded from 1.8 or restored from MDT file-level backup.
7058          * For the whole directory, only dotdot entry have no FID-in-dirent
7059          * and needs to get FID from LMA when readdir, it will not affect the
7060          * performance much.
7061          */
7062         if (dotdot && !osd_dotdot_has_space(de)) {
7063                 *attr |= LUDA_UNKNOWN;
7064
7065                 GOTO(out, rc = 0);
7066         }
7067
7068         if (lma != NULL) {
7069                 if (lu_fid_eq(fid, &lma->lma_self_fid))
7070                         GOTO(out, rc = 0);
7071
7072                 if (unlikely(lma->lma_compat & LMAC_NOT_IN_OI)) {
7073                         struct lu_fid *tfid = &lma->lma_self_fid;
7074
7075                         if (likely(dotdot &&
7076                                    fid_seq(tfid) == FID_SEQ_LOCAL_FILE &&
7077                                    fid_oid(tfid) == REMOTE_PARENT_DIR_OID)) {
7078                                 /*
7079                                  * It must be REMOTE_PARENT_DIR and as the
7080                                  * 'dotdot' entry of remote directory
7081                                  */
7082                                 *attr |= LUDA_IGNORE;
7083                         } else {
7084                                 CDEBUG(D_LFSCK, "%s: expect remote agent "
7085                                        "parent directory, but got %.*s under "
7086                                        "dir = %lu/%u with the FID "DFID"\n",
7087                                        devname, ent->oied_namelen,
7088                                        ent->oied_name, dir->i_ino,
7089                                        dir->i_generation, PFID(tfid));
7090
7091                                 *attr |= LUDA_UNKNOWN;
7092                         }
7093
7094                         GOTO(out, rc = 0);
7095                 }
7096         }
7097
7098         if (!fid_is_zero(fid)) {
7099                 rc = osd_verify_ent_by_linkea(env, inode, pfid, ent->oied_name,
7100                                               ent->oied_namelen);
7101                 if (rc == -ENOENT ||
7102                     (rc == -ENODATA &&
7103                      !(dev->od_scrub.os_scrub.os_file.sf_flags & SF_UPGRADE))) {
7104                         /*
7105                          * linkEA does not recognize the dirent entry,
7106                          * it may because the dirent entry corruption
7107                          * and points to other's inode.
7108                          */
7109                         CDEBUG(D_LFSCK, "%s: the target inode does not "
7110                                "recognize the dirent, dir = %lu/%u, "
7111                                " name = %.*s, ino = %llu, "
7112                                DFID": rc = %d\n", devname, dir->i_ino,
7113                                dir->i_generation, ent->oied_namelen,
7114                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
7115                         *attr |= LUDA_UNKNOWN;
7116
7117                         GOTO(out, rc = 0);
7118                 }
7119
7120                 if (rc && rc != -ENODATA) {
7121                         CDEBUG(D_LFSCK, "%s: fail to verify FID in the dirent, "
7122                                "dir = %lu/%u, name = %.*s, ino = %llu, "
7123                                DFID": rc = %d\n", devname, dir->i_ino,
7124                                dir->i_generation, ent->oied_namelen,
7125                                ent->oied_name, ent->oied_ino, PFID(fid), rc);
7126                         *attr |= LUDA_UNKNOWN;
7127
7128                         GOTO(out, rc = 0);
7129                 }
7130         }
7131
7132         if (lma != NULL) {
7133                 /*
7134                  * linkEA recognizes the dirent entry, the FID-in-LMA is
7135                  * valid, trusted, in spite of fid_is_sane(fid) or not.
7136                  */
7137                 if (*attr & LUDA_VERIFY_DRYRUN) {
7138                         *fid = lma->lma_self_fid;
7139                         *attr |= LUDA_REPAIR;
7140
7141                         GOTO(out, rc = 0);
7142                 }
7143
7144                 if (jh == NULL) {
7145                         brelse(bh);
7146                         dev->od_dirent_journal = 1;
7147                         if (hlock != NULL) {
7148                                 ldiskfs_htree_unlock(hlock);
7149                                 hlock = NULL;
7150                         } else {
7151                                 up_read(&obj->oo_ext_idx_sem);
7152                         }
7153
7154                         goto again;
7155                 }
7156
7157                 *fid = lma->lma_self_fid;
7158                 dirty = true;
7159                 /* Update or append the FID-in-dirent. */
7160                 rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
7161                                          bh, de, hlock, dotdot);
7162                 if (rc == 0)
7163                         *attr |= LUDA_REPAIR;
7164                 else
7165                         CDEBUG(D_LFSCK, "%s: fail to re-insert FID after "
7166                                "the dirent, dir = %lu/%u, name = %.*s, "
7167                                "ino = %llu, "DFID": rc = %d\n",
7168                                devname, dir->i_ino, dir->i_generation,
7169                                ent->oied_namelen, ent->oied_name,
7170                                ent->oied_ino, PFID(fid), rc);
7171         } else {
7172                 /* lma is NULL, trust the FID-in-dirent if it is valid. */
7173                 if (*attr & LUDA_VERIFY_DRYRUN) {
7174                         if (fid_is_sane(fid)) {
7175                                 *attr |= LUDA_REPAIR;
7176                         } else if (dev->od_index == 0) {
7177                                 lu_igif_build(fid, inode->i_ino,
7178                                               inode->i_generation);
7179                                 *attr |= LUDA_UPGRADE;
7180                         }
7181
7182                         GOTO(out, rc = 0);
7183                 }
7184
7185                 if (jh == NULL) {
7186                         brelse(bh);
7187                         dev->od_dirent_journal = 1;
7188                         if (hlock != NULL) {
7189                                 ldiskfs_htree_unlock(hlock);
7190                                 hlock = NULL;
7191                         } else {
7192                                 up_read(&obj->oo_ext_idx_sem);
7193                         }
7194
7195                         goto again;
7196                 }
7197
7198                 dirty = true;
7199                 if (unlikely(fid_is_sane(fid))) {
7200                         /*
7201                          * FID-in-dirent exists, but FID-in-LMA is lost.
7202                          * Trust the FID-in-dirent, and add FID-in-LMA.
7203                          */
7204                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
7205                         if (rc == 0)
7206                                 *attr |= LUDA_REPAIR;
7207                         else
7208                                 CDEBUG(D_LFSCK, "%s: fail to set LMA for "
7209                                        "update dirent, dir = %lu/%u, "
7210                                        "name = %.*s, ino = %llu, "
7211                                        DFID": rc = %d\n",
7212                                        devname, dir->i_ino, dir->i_generation,
7213                                        ent->oied_namelen, ent->oied_name,
7214                                        ent->oied_ino, PFID(fid), rc);
7215                 } else if (dev->od_index == 0) {
7216                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
7217                         /*
7218                          * It is probably IGIF object. Only aappend the
7219                          * FID-in-dirent. OI scrub will process FID-in-LMA.
7220                          */
7221                         rc = osd_dirent_reinsert(env, dev, jh, dentry, fid,
7222                                                  bh, de, hlock, dotdot);
7223                         if (rc == 0)
7224                                 *attr |= LUDA_UPGRADE;
7225                         else
7226                                 CDEBUG(D_LFSCK, "%s: fail to append IGIF "
7227                                        "after the dirent, dir = %lu/%u, "
7228                                        "name = %.*s, ino = %llu, "
7229                                        DFID": rc = %d\n",
7230                                        devname, dir->i_ino, dir->i_generation,
7231                                        ent->oied_namelen, ent->oied_name,
7232                                        ent->oied_ino, PFID(fid), rc);
7233                 }
7234         }
7235
7236         GOTO(out, rc);
7237
7238 out:
7239         if (!IS_ERR(bh))
7240                 brelse(bh);
7241         if (hlock != NULL) {
7242                 ldiskfs_htree_unlock(hlock);
7243         } else {
7244                 if (dev->od_dirent_journal != 0)
7245                         up_write(&obj->oo_ext_idx_sem);
7246                 else
7247                         up_read(&obj->oo_ext_idx_sem);
7248         }
7249
7250         if (jh != NULL)
7251                 ldiskfs_journal_stop(jh);
7252
7253 out_inode:
7254         iput(inode);
7255         if (rc >= 0 && !dirty)
7256                 dev->od_dirent_journal = 0;
7257
7258         return rc;
7259 }
7260
7261 /**
7262  * Returns the value at current position from iterator's in memory structure.
7263  *
7264  * \param di struct osd_it_ea, iterator's in memory structure
7265  * \param attr attr requested for dirent.
7266  * \param lde lustre dirent
7267  *
7268  * \retval   0 no error and \param lde has correct lustre dirent.
7269  * \retval -ve on error
7270  */
7271 static inline int osd_it_ea_rec(const struct lu_env *env,
7272                                 const struct dt_it *di,
7273                                 struct dt_rec *dtrec, __u32 attr)
7274 {
7275         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
7276         struct osd_object      *obj   = it->oie_obj;
7277         struct osd_device      *dev   = osd_obj2dev(obj);
7278         struct osd_thread_info *oti   = osd_oti_get(env);
7279         struct osd_inode_id    *id    = &oti->oti_id;
7280         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
7281         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
7282         __u32 ino = it->oie_dirent->oied_ino;
7283         int rc = 0;
7284
7285         ENTRY;
7286
7287         LASSERT(!is_remote_parent_ino(dev, obj->oo_inode->i_ino));
7288
7289         if (attr & LUDA_VERIFY) {
7290                 if (unlikely(is_remote_parent_ino(dev, ino))) {
7291                         attr |= LUDA_IGNORE;
7292                         /*
7293                          * If the parent is on remote MDT, and there
7294                          * is no FID-in-dirent, then we have to get
7295                          * the parent FID from the linkEA.
7296                          */
7297                         if (!fid_is_sane(fid) &&
7298                             it->oie_dirent->oied_namelen == 2 &&
7299                             it->oie_dirent->oied_name[0] == '.' &&
7300                             it->oie_dirent->oied_name[1] == '.')
7301                                 osd_get_pfid_from_linkea(env, obj, fid);
7302                 } else {
7303                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
7304                                                      &attr);
7305                 }
7306
7307                 if (!fid_is_sane(fid))
7308                         attr |= LUDA_UNKNOWN;
7309         } else {
7310                 attr &= ~LU_DIRENT_ATTRS_MASK;
7311                 if (!fid_is_sane(fid)) {
7312                         bool is_dotdot = false;
7313
7314                         if (it->oie_dirent->oied_namelen == 2 &&
7315                             it->oie_dirent->oied_name[0] == '.' &&
7316                             it->oie_dirent->oied_name[1] == '.')
7317                                 is_dotdot = true;
7318                         /*
7319                          * If the parent is on remote MDT, and there
7320                          * is no FID-in-dirent, then we have to get
7321                          * the parent FID from the linkEA.
7322                          */
7323                         if (is_remote_parent_ino(dev, ino) && is_dotdot) {
7324                                 rc = osd_get_pfid_from_linkea(env, obj, fid);
7325                         } else {
7326                                 if (is_dotdot == false &&
7327                                     OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
7328                                         RETURN(-ENOENT);
7329
7330                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
7331                         }
7332                 }
7333         }
7334
7335         /* Pack the entry anyway, at least the offset is right. */
7336         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
7337                            it->oie_dirent->oied_name,
7338                            it->oie_dirent->oied_namelen,
7339                            it->oie_dirent->oied_type, attr);
7340
7341         RETURN(rc > 0 ? 0 : rc);
7342 }
7343
7344 /**
7345  * Returns the record size size at current position.
7346  *
7347  * This function will return record(lu_dirent) size in bytes.
7348  *
7349  * \param[in] env       execution environment
7350  * \param[in] di        iterator's in memory structure
7351  * \param[in] attr      attribute of the entry, only requires LUDA_TYPE to
7352  *                      calculate the lu_dirent size.
7353  *
7354  * \retval      record size(in bytes & in memory) of the current lu_dirent
7355  *              entry.
7356  */
7357 static int osd_it_ea_rec_size(const struct lu_env *env, const struct dt_it *di,
7358                               __u32 attr)
7359 {
7360         struct osd_it_ea *it = (struct osd_it_ea *)di;
7361
7362         return lu_dirent_calc_size(it->oie_dirent->oied_namelen, attr);
7363 }
7364
7365 /**
7366  * Returns a cookie for current position of the iterator head, so that
7367  * user can use this cookie to load/start the iterator next time.
7368  *
7369  * \param di iterator's in memory structure
7370  *
7371  * \retval cookie for current position, on success
7372  */
7373 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
7374 {
7375         struct osd_it_ea *it = (struct osd_it_ea *)di;
7376
7377         return it->oie_dirent->oied_off;
7378 }
7379
7380 /**
7381  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
7382  * to load a directory entry at a time and stored it i inn,
7383  * in iterator's in-memory data structure.
7384  *
7385  * \param di struct osd_it_ea, iterator's in memory structure
7386  *
7387  * \retval +ve on success
7388  * \retval -ve on error
7389  */
7390 static int osd_it_ea_load(const struct lu_env *env,
7391                           const struct dt_it *di, __u64 hash)
7392 {
7393         struct osd_it_ea *it = (struct osd_it_ea *)di;
7394         int rc;
7395
7396         ENTRY;
7397         it->oie_file.f_pos = hash;
7398
7399         rc =  osd_ldiskfs_it_fill(env, di);
7400         if (rc > 0)
7401                 rc = -ENODATA;
7402
7403         if (rc == 0)
7404                 rc = 1;
7405
7406         RETURN(rc);
7407 }
7408
7409 /**
7410  * Index lookup function for interoperability mode (b11826).
7411  *
7412  * \param key,  key i.e. file name to be searched
7413  *
7414  * \retval +ve, on success
7415  * \retval -ve, on error
7416  */
7417 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
7418                                struct dt_rec *rec, const struct dt_key *key)
7419 {
7420         struct osd_object *obj = osd_dt_obj(dt);
7421         int rc = 0;
7422
7423         ENTRY;
7424
7425         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
7426         LINVRNT(osd_invariant(obj));
7427
7428         rc = osd_ea_lookup_rec(env, obj, rec, key);
7429         if (rc == 0)
7430                 rc = 1;
7431         RETURN(rc);
7432 }
7433
7434 /**
7435  * Index and Iterator operations for interoperability
7436  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
7437  */
7438 static const struct dt_index_operations osd_index_ea_ops = {
7439         .dio_lookup         = osd_index_ea_lookup,
7440         .dio_declare_insert = osd_index_declare_ea_insert,
7441         .dio_insert         = osd_index_ea_insert,
7442         .dio_declare_delete = osd_index_declare_ea_delete,
7443         .dio_delete         = osd_index_ea_delete,
7444         .dio_it     = {
7445                 .init     = osd_it_ea_init,
7446                 .fini     = osd_it_ea_fini,
7447                 .get      = osd_it_ea_get,
7448                 .put      = osd_it_ea_put,
7449                 .next     = osd_it_ea_next,
7450                 .key      = osd_it_ea_key,
7451                 .key_size = osd_it_ea_key_size,
7452                 .rec      = osd_it_ea_rec,
7453                 .rec_size = osd_it_ea_rec_size,
7454                 .store    = osd_it_ea_store,
7455                 .load     = osd_it_ea_load
7456         }
7457 };
7458
7459 static void *osd_key_init(const struct lu_context *ctx,
7460                           struct lu_context_key *key)
7461 {
7462         struct osd_thread_info *info;
7463
7464         OBD_ALLOC_PTR(info);
7465         if (info == NULL)
7466                 return ERR_PTR(-ENOMEM);
7467
7468         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7469         if (info->oti_it_ea_buf == NULL)
7470                 goto out_free_info;
7471
7472         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
7473
7474         info->oti_hlock = ldiskfs_htree_lock_alloc();
7475         if (info->oti_hlock == NULL)
7476                 goto out_free_ea;
7477
7478         return info;
7479
7480 out_free_ea:
7481         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7482 out_free_info:
7483         OBD_FREE_PTR(info);
7484         return ERR_PTR(-ENOMEM);
7485 }
7486
7487 static void osd_key_fini(const struct lu_context *ctx,
7488                          struct lu_context_key *key, void *data)
7489 {
7490         struct osd_thread_info *info = data;
7491         struct ldiskfs_inode_info *lli = LDISKFS_I(info->oti_inode);
7492         struct osd_idmap_cache *idc = info->oti_ins_cache;
7493
7494         if (info->oti_dio_pages) {
7495                 int i;
7496                 for (i = 0; i < PTLRPC_MAX_BRW_PAGES; i++) {
7497                         if (info->oti_dio_pages[i])
7498                                 __free_page(info->oti_dio_pages[i]);
7499                 }
7500                 OBD_FREE(info->oti_dio_pages,
7501                          sizeof(struct page *) * PTLRPC_MAX_BRW_PAGES);
7502         }
7503
7504         if (info->oti_inode != NULL)
7505                 OBD_FREE_PTR(lli);
7506         if (info->oti_hlock != NULL)
7507                 ldiskfs_htree_lock_free(info->oti_hlock);
7508         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
7509         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
7510         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
7511         lu_buf_free(&info->oti_iobuf.dr_lnb_buf);
7512         lu_buf_free(&info->oti_big_buf);
7513         if (idc != NULL) {
7514                 LASSERT(info->oti_ins_cache_size > 0);
7515                 OBD_FREE(idc, sizeof(*idc) * info->oti_ins_cache_size);
7516                 info->oti_ins_cache = NULL;
7517                 info->oti_ins_cache_size = 0;
7518         }
7519         OBD_FREE_PTR(info);
7520 }
7521
7522 static void osd_key_exit(const struct lu_context *ctx,
7523                          struct lu_context_key *key, void *data)
7524 {
7525         struct osd_thread_info *info = data;
7526
7527         LASSERT(info->oti_r_locks == 0);
7528         LASSERT(info->oti_w_locks == 0);
7529         LASSERT(info->oti_txns    == 0);
7530 }
7531
7532 /* type constructor/destructor: osd_type_init, osd_type_fini */
7533 LU_TYPE_INIT_FINI(osd, &osd_key);
7534
7535 struct lu_context_key osd_key = {
7536         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
7537         .lct_init = osd_key_init,
7538         .lct_fini = osd_key_fini,
7539         .lct_exit = osd_key_exit
7540 };
7541
7542
7543 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
7544                            const char *name, struct lu_device *next)
7545 {
7546         struct osd_device *osd = osd_dev(d);
7547
7548         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname)) >=
7549             sizeof(osd->od_svname))
7550                 return -E2BIG;
7551         return osd_procfs_init(osd, name);
7552 }
7553
7554 static int osd_fid_init(const struct lu_env *env, struct osd_device *osd)
7555 {
7556         struct seq_server_site *ss = osd_seq_site(osd);
7557         int rc;
7558
7559         ENTRY;
7560
7561         if (osd->od_is_ost || osd->od_cl_seq != NULL)
7562                 RETURN(0);
7563
7564         if (unlikely(ss == NULL))
7565                 RETURN(-ENODEV);
7566
7567         OBD_ALLOC_PTR(osd->od_cl_seq);
7568         if (osd->od_cl_seq == NULL)
7569                 RETURN(-ENOMEM);
7570
7571         rc = seq_client_init(osd->od_cl_seq, NULL, LUSTRE_SEQ_METADATA,
7572                              osd->od_svname, ss->ss_server_seq);
7573         if (rc != 0) {
7574                 OBD_FREE_PTR(osd->od_cl_seq);
7575                 osd->od_cl_seq = NULL;
7576                 RETURN(rc);
7577         }
7578
7579         if (ss->ss_node_id == 0) {
7580                 /*
7581                  * If the OSD on the sequence controller(MDT0), then allocate
7582                  * sequence here, otherwise allocate sequence after connected
7583                  * to MDT0 (see mdt_register_lwp_callback()).
7584                  */
7585                 rc = seq_server_alloc_meta(osd->od_cl_seq->lcs_srv,
7586                                    &osd->od_cl_seq->lcs_space, env);
7587         }
7588
7589         RETURN(rc);
7590 }
7591
7592 static void osd_fid_fini(const struct lu_env *env, struct osd_device *osd)
7593 {
7594         if (osd->od_cl_seq == NULL)
7595                 return;
7596
7597         seq_client_fini(osd->od_cl_seq);
7598         OBD_FREE_PTR(osd->od_cl_seq);
7599         osd->od_cl_seq = NULL;
7600 }
7601
7602 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
7603 {
7604         ENTRY;
7605
7606         /* shutdown quota slave instance associated with the device */
7607         if (o->od_quota_slave_md != NULL) {
7608                 struct qsd_instance *qsd = o->od_quota_slave_md;
7609
7610                 o->od_quota_slave_md = NULL;
7611                 qsd_fini(env, qsd);
7612         }
7613
7614         if (o->od_quota_slave_dt != NULL) {
7615                 struct qsd_instance *qsd = o->od_quota_slave_dt;
7616
7617                 o->od_quota_slave_dt = NULL;
7618                 qsd_fini(env, qsd);
7619         }
7620
7621         osd_fid_fini(env, o);
7622         osd_scrub_cleanup(env, o);
7623
7624         RETURN(0);
7625 }
7626
7627 static void osd_umount(const struct lu_env *env, struct osd_device *o)
7628 {
7629         ENTRY;
7630
7631         if (o->od_mnt != NULL) {
7632                 shrink_dcache_sb(osd_sb(o));
7633                 osd_sync(env, &o->od_dt_dev);
7634
7635                 mntput(o->od_mnt);
7636                 o->od_mnt = NULL;
7637         }
7638
7639         EXIT;
7640 }
7641
7642 static int osd_mount(const struct lu_env *env,
7643                      struct osd_device *o, struct lustre_cfg *cfg)
7644 {
7645         const char *name = lustre_cfg_string(cfg, 0);
7646         const char *dev = lustre_cfg_string(cfg, 1);
7647         const char *opts;
7648         unsigned long page, s_flags, lmd_flags = 0;
7649         struct page *__page;
7650         struct file_system_type *type;
7651         char *options = NULL;
7652         char *str;
7653         struct osd_thread_info *info = osd_oti_get(env);
7654         struct lu_fid *fid = &info->oti_fid;
7655         struct inode *inode;
7656         int rc = 0, force_over_512tb = 0;
7657
7658         ENTRY;
7659
7660         if (o->od_mnt != NULL)
7661                 RETURN(0);
7662
7663         if (strlen(dev) >= sizeof(o->od_mntdev))
7664                 RETURN(-E2BIG);
7665         strcpy(o->od_mntdev, dev);
7666
7667         str = lustre_cfg_string(cfg, 2);
7668         s_flags = simple_strtoul(str, NULL, 0);
7669         str = strstr(str, ":");
7670         if (str)
7671                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
7672         opts = lustre_cfg_string(cfg, 3);
7673 #ifdef __BIG_ENDIAN
7674         if (opts == NULL || strstr(opts, "bigendian_extents") == NULL) {
7675                 CERROR("%s: device %s extents feature is not guaranteed to "
7676                        "work on big-endian systems. Use \"bigendian_extents\" "
7677                        "mount option to override.\n", name, dev);
7678                 RETURN(-EINVAL);
7679         }
7680 #endif
7681 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 53, 0)
7682         if (opts != NULL && strstr(opts, "force_over_128tb") != NULL) {
7683                 CWARN("force_over_128tb option is deprecated. "
7684                       "Filesystems less than 512TB can be created without any "
7685                       "force options. Use force_over_512tb option for "
7686                       "filesystems greater than 512TB.\n");
7687         }
7688 #endif
7689 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 1, 53, 0)
7690         if (opts != NULL && strstr(opts, "force_over_256tb") != NULL) {
7691                 CWARN("force_over_256tb option is deprecated. "
7692                       "Filesystems less than 512TB can be created without any "
7693                       "force options. Use force_over_512tb option for "
7694                       "filesystems greater than 512TB.\n");
7695         }
7696 #endif
7697
7698         if (opts != NULL && strstr(opts, "force_over_512tb") != NULL)
7699                 force_over_512tb = 1;
7700
7701         __page = alloc_page(GFP_KERNEL);
7702         if (__page == NULL)
7703                 GOTO(out, rc = -ENOMEM);
7704         page = (unsigned long)page_address(__page);
7705         options = (char *)page;
7706         *options = '\0';
7707         if (opts != NULL) {
7708                 /* strip out the options for back compatiblity */
7709                 static char *sout[] = {
7710                         "mballoc",
7711                         "iopen",
7712                         "noiopen",
7713                         "iopen_nopriv",
7714                         "extents",
7715                         "noextents",
7716                         /* strip out option we processed in osd */
7717                         "bigendian_extents",
7718                         "force_over_128tb",
7719                         "force_over_256tb",
7720                         "force_over_512tb",
7721                         "resetoi",
7722                         NULL
7723                 };
7724                 strncat(options, opts, PAGE_SIZE);
7725                 for (rc = 0, str = options; sout[rc]; ) {
7726                         char *op = strstr(str, sout[rc]);
7727
7728                         if (op == NULL) {
7729                                 rc++;
7730                                 str = options;
7731                                 continue;
7732                         }
7733                         if (op == options || *(op - 1) == ',') {
7734                                 str = op + strlen(sout[rc]);
7735                                 if (*str == ',' || *str == '\0') {
7736                                         *str == ',' ? str++ : str;
7737                                         memmove(op, str, strlen(str) + 1);
7738                                 }
7739                         }
7740                         for (str = op; *str != ',' && *str != '\0'; str++)
7741                                 ;
7742                 }
7743         } else {
7744                 strncat(options, "user_xattr,acl", PAGE_SIZE);
7745         }
7746
7747         /* Glom up mount options */
7748         if (*options != '\0')
7749                 strncat(options, ",", PAGE_SIZE);
7750         strncat(options, "no_mbcache,nodelalloc", PAGE_SIZE);
7751
7752         type = get_fs_type("ldiskfs");
7753         if (!type) {
7754                 CERROR("%s: cannot find ldiskfs module\n", name);
7755                 GOTO(out, rc = -ENODEV);
7756         }
7757
7758         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
7759         module_put(type->owner);
7760
7761         if (IS_ERR(o->od_mnt)) {
7762                 rc = PTR_ERR(o->od_mnt);
7763                 o->od_mnt = NULL;
7764                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
7765                 GOTO(out, rc);
7766         }
7767
7768         if (ldiskfs_blocks_count(LDISKFS_SB(osd_sb(o))->s_es) <<
7769                                  osd_sb(o)->s_blocksize_bits > 512ULL << 40 &&
7770                                  force_over_512tb == 0) {
7771                 CERROR("%s: device %s LDISKFS does not support filesystems "
7772                        "greater than 512TB and can cause data corruption. "
7773                        "Use \"force_over_512tb\" mount option to override.\n",
7774                        name, dev);
7775                 GOTO(out_mnt, rc = -EINVAL);
7776         }
7777
7778         if (lmd_flags & LMD_FLG_DEV_RDONLY) {
7779                 if (priv_dev_set_rdonly) {
7780                         priv_dev_set_rdonly(osd_sb(o)->s_bdev);
7781                         o->od_dt_dev.dd_rdonly = 1;
7782                         LCONSOLE_WARN("%s: set dev_rdonly on this device\n",
7783                                       name);
7784                 } else {
7785                         LCONSOLE_WARN("%s: not support dev_rdonly on this device",
7786                                       name);
7787
7788                         GOTO(out_mnt, rc = -EOPNOTSUPP);
7789                 }
7790         } else if (priv_dev_check_rdonly &&
7791                    priv_dev_check_rdonly(osd_sb(o)->s_bdev)) {
7792                 CERROR("%s: underlying device %s is marked as "
7793                        "read-only. Setup failed\n", name, dev);
7794
7795                 GOTO(out_mnt, rc = -EROFS);
7796         }
7797
7798         if (!ldiskfs_has_feature_journal(o->od_mnt->mnt_sb)) {
7799                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
7800                 GOTO(out_mnt, rc = -EINVAL);
7801         }
7802
7803 #ifdef LDISKFS_MOUNT_DIRDATA
7804         if (ldiskfs_has_feature_dirdata(o->od_mnt->mnt_sb))
7805                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
7806         else if (strstr(name, "MDT")) /* don't complain for MGT or OSTs */
7807                 CWARN("%s: device %s was upgraded from Lustre-1.x without "
7808                       "enabling the dirdata feature. If you do not want to "
7809                       "downgrade to Lustre-1.x again, you can enable it via "
7810                       "'tune2fs -O dirdata device'\n", name, dev);
7811 #endif
7812         inode = osd_sb(o)->s_root->d_inode;
7813         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
7814         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
7815         if (rc != 0) {
7816                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
7817                 GOTO(out_mnt, rc);
7818         }
7819
7820         if (lmd_flags & LMD_FLG_NOSCRUB)
7821                 o->od_auto_scrub_interval = AS_NEVER;
7822
7823         if (blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev))) {
7824                 /* do not use pagecache with flash-backed storage */
7825                 o->od_writethrough_cache = 0;
7826                 o->od_read_cache = 0;
7827         }
7828
7829         GOTO(out, rc = 0);
7830
7831 out_mnt:
7832         mntput(o->od_mnt);
7833         o->od_mnt = NULL;
7834
7835 out:
7836         if (__page)
7837                 __free_page(__page);
7838
7839         return rc;
7840 }
7841
7842 static struct lu_device *osd_device_fini(const struct lu_env *env,
7843                                          struct lu_device *d)
7844 {
7845         struct osd_device *o = osd_dev(d);
7846
7847         ENTRY;
7848
7849         osd_index_backup(env, o, false);
7850         osd_shutdown(env, o);
7851         osd_procfs_fini(o);
7852         if (o->od_oi_table != NULL)
7853                 osd_oi_fini(osd_oti_get(env), o);
7854         osd_obj_map_fini(o);
7855         osd_umount(env, o);
7856
7857         RETURN(NULL);
7858 }
7859
7860 static int osd_device_init0(const struct lu_env *env,
7861                             struct osd_device *o,
7862                             struct lustre_cfg *cfg)
7863 {
7864         struct lu_device *l = osd2lu_dev(o);
7865         struct osd_thread_info *info;
7866         int cplen = 0;
7867         char *opts = NULL;
7868         bool restored = false;
7869         int rc;
7870
7871         /* if the module was re-loaded, env can loose its keys */
7872         rc = lu_env_refill((struct lu_env *)env);
7873         if (rc)
7874                 GOTO(out, rc);
7875         info = osd_oti_get(env);
7876         LASSERT(info);
7877
7878         l->ld_ops = &osd_lu_ops;
7879         o->od_dt_dev.dd_ops = &osd_dt_ops;
7880
7881         spin_lock_init(&o->od_osfs_lock);
7882         mutex_init(&o->od_otable_mutex);
7883         INIT_LIST_HEAD(&o->od_orphan_list);
7884         INIT_LIST_HEAD(&o->od_index_backup_list);
7885         INIT_LIST_HEAD(&o->od_index_restore_list);
7886         spin_lock_init(&o->od_lock);
7887         o->od_index_backup_policy = LIBP_NONE;
7888         o->od_t10_type = 0;
7889
7890         o->od_read_cache = 1;
7891         o->od_writethrough_cache = 1;
7892         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
7893
7894         o->od_auto_scrub_interval = AS_DEFAULT;
7895
7896         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
7897                         sizeof(o->od_svname));
7898         if (cplen >= sizeof(o->od_svname)) {
7899                 rc = -E2BIG;
7900                 GOTO(out, rc);
7901         }
7902
7903         o->od_index_backup_stop = 0;
7904         o->od_index = -1; /* -1 means index is invalid */
7905         rc = server_name2index(o->od_svname, &o->od_index, NULL);
7906         if (rc == LDD_F_SV_TYPE_OST)
7907                 o->od_is_ost = 1;
7908
7909         o->od_full_scrub_ratio = OFSR_DEFAULT;
7910         o->od_full_scrub_threshold_rate = FULL_SCRUB_THRESHOLD_RATE_DEFAULT;
7911         rc = osd_mount(env, o, cfg);
7912         if (rc != 0)
7913                 GOTO(out, rc);
7914
7915         /* Can only check block device after mount */
7916         o->od_nonrotational =
7917                 blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev));
7918
7919         rc = osd_obj_map_init(env, o);
7920         if (rc != 0)
7921                 GOTO(out_mnt, rc);
7922
7923         rc = lu_site_init(&o->od_site, l);
7924         if (rc != 0)
7925                 GOTO(out_compat, rc);
7926         o->od_site.ls_bottom_dev = l;
7927
7928         rc = lu_site_init_finish(&o->od_site);
7929         if (rc != 0)
7930                 GOTO(out_site, rc);
7931
7932         opts = lustre_cfg_string(cfg, 3);
7933         if (opts && strstr(opts, "resetoi"))
7934                 restored = true;
7935
7936         INIT_LIST_HEAD(&o->od_ios_list);
7937         /* setup scrub, including OI files initialization */
7938         o->od_in_init = 1;
7939         rc = osd_scrub_setup(env, o, restored);
7940         o->od_in_init = 0;
7941         if (rc < 0)
7942                 GOTO(out_site, rc);
7943
7944         rc = osd_procfs_init(o, o->od_svname);
7945         if (rc != 0) {
7946                 CERROR("%s: can't initialize procfs: rc = %d\n",
7947                        o->od_svname, rc);
7948                 GOTO(out_scrub, rc);
7949         }
7950
7951         LASSERT(l->ld_site->ls_linkage.next != NULL);
7952         LASSERT(l->ld_site->ls_linkage.prev != NULL);
7953
7954         /* initialize quota slave instance */
7955         /* currently it's no need to prepare qsd_instance_md for OST */
7956         if (!o->od_is_ost) {
7957                 o->od_quota_slave_md = qsd_init(env, o->od_svname,
7958                                                 &o->od_dt_dev,
7959                                                 o->od_proc_entry, true);
7960                 if (IS_ERR(o->od_quota_slave_md)) {
7961                         rc = PTR_ERR(o->od_quota_slave_md);
7962                         o->od_quota_slave_md = NULL;
7963                         GOTO(out_procfs, rc);
7964                 }
7965         }
7966
7967         o->od_quota_slave_dt = qsd_init(env, o->od_svname, &o->od_dt_dev,
7968                                         o->od_proc_entry, false);
7969
7970         if (IS_ERR(o->od_quota_slave_dt)) {
7971                 if (o->od_quota_slave_md != NULL) {
7972                         qsd_fini(env, o->od_quota_slave_md);
7973                         o->od_quota_slave_md = NULL;
7974                 }
7975
7976                 rc = PTR_ERR(o->od_quota_slave_dt);
7977                 o->od_quota_slave_dt = NULL;
7978                 GOTO(out_procfs, rc);
7979         }
7980
7981         RETURN(0);
7982
7983 out_procfs:
7984         osd_procfs_fini(o);
7985 out_scrub:
7986         osd_scrub_cleanup(env, o);
7987 out_site:
7988         lu_site_fini(&o->od_site);
7989 out_compat:
7990         osd_obj_map_fini(o);
7991 out_mnt:
7992         osd_umount(env, o);
7993 out:
7994         return rc;
7995 }
7996
7997 static struct lu_device *osd_device_alloc(const struct lu_env *env,
7998                                           struct lu_device_type *t,
7999                                           struct lustre_cfg *cfg)
8000 {
8001         struct osd_device *o;
8002         int rc;
8003
8004         OBD_ALLOC_PTR(o);
8005         if (o == NULL)
8006                 return ERR_PTR(-ENOMEM);
8007
8008         rc = dt_device_init(&o->od_dt_dev, t);
8009         if (rc == 0) {
8010                 /*
8011                  * Because the ctx might be revived in dt_device_init,
8012                  * refill the env here
8013                  */
8014                 lu_env_refill((struct lu_env *)env);
8015                 rc = osd_device_init0(env, o, cfg);
8016                 if (rc)
8017                         dt_device_fini(&o->od_dt_dev);
8018         }
8019
8020         if (unlikely(rc != 0))
8021                 OBD_FREE_PTR(o);
8022
8023         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
8024 }
8025
8026 static struct lu_device *osd_device_free(const struct lu_env *env,
8027                                          struct lu_device *d)
8028 {
8029         struct osd_device *o = osd_dev(d);
8030
8031         ENTRY;
8032
8033         /* XXX: make osd top device in order to release reference */
8034         d->ld_site->ls_top_dev = d;
8035         lu_site_purge(env, d->ld_site, -1);
8036         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
8037                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
8038                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
8039         }
8040         lu_site_fini(&o->od_site);
8041         dt_device_fini(&o->od_dt_dev);
8042         OBD_FREE_PTR(o);
8043         RETURN(NULL);
8044 }
8045
8046 static int osd_process_config(const struct lu_env *env,
8047                               struct lu_device *d, struct lustre_cfg *cfg)
8048 {
8049         struct osd_device *o = osd_dev(d);
8050         int rc;
8051
8052         ENTRY;
8053
8054         switch (cfg->lcfg_command) {
8055         case LCFG_SETUP:
8056                 rc = osd_mount(env, o, cfg);
8057                 break;
8058         case LCFG_CLEANUP:
8059                 /*
8060                  * For the case LCFG_PRE_CLEANUP is not called in advance,
8061                  * that may happend if hit failure during mount process.
8062                  */
8063                 osd_index_backup(env, o, false);
8064                 lu_dev_del_linkage(d->ld_site, d);
8065                 rc = osd_shutdown(env, o);
8066                 break;
8067         case LCFG_PARAM:
8068                 LASSERT(&o->od_dt_dev);
8069                 rc = class_process_proc_param(PARAM_OSD, lprocfs_osd_obd_vars,
8070                                               cfg, &o->od_dt_dev);
8071                 if (rc > 0 || rc == -ENOSYS) {
8072                         rc = class_process_proc_param(PARAM_OST,
8073                                                       lprocfs_osd_obd_vars,
8074                                                       cfg, &o->od_dt_dev);
8075                         if (rc > 0)
8076                                 rc = 0;
8077                 }
8078                 break;
8079         case LCFG_PRE_CLEANUP:
8080                 osd_scrub_stop(o);
8081                 osd_index_backup(env, o,
8082                                  o->od_index_backup_policy != LIBP_NONE);
8083                 rc = 0;
8084                 break;
8085         default:
8086                 rc = -ENOSYS;
8087         }
8088
8089         RETURN(rc);
8090 }
8091
8092 static int osd_recovery_complete(const struct lu_env *env,
8093                                  struct lu_device *d)
8094 {
8095         struct osd_device *osd = osd_dev(d);
8096         int rc = 0;
8097
8098         ENTRY;
8099
8100         if (osd->od_quota_slave_md == NULL && osd->od_quota_slave_dt == NULL)
8101                 RETURN(0);
8102
8103         /*
8104          * start qsd instance on recovery completion, this notifies the quota
8105          * slave code that we are about to process new requests now
8106          */
8107         rc = qsd_start(env, osd->od_quota_slave_dt);
8108         if (rc == 0 && osd->od_quota_slave_md != NULL)
8109                 rc = qsd_start(env, osd->od_quota_slave_md);
8110
8111         RETURN(rc);
8112 }
8113
8114 /*
8115  * we use exports to track all osd users
8116  */
8117 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
8118                            struct obd_device *obd, struct obd_uuid *cluuid,
8119                            struct obd_connect_data *data, void *localdata)
8120 {
8121         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8122         struct lustre_handle conn;
8123         int rc;
8124
8125         ENTRY;
8126
8127         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
8128
8129         rc = class_connect(&conn, obd, cluuid);
8130         if (rc)
8131                 RETURN(rc);
8132
8133         *exp = class_conn2export(&conn);
8134
8135         spin_lock(&osd->od_osfs_lock);
8136         osd->od_connects++;
8137         spin_unlock(&osd->od_osfs_lock);
8138
8139         RETURN(0);
8140 }
8141
8142 /*
8143  * once last export (we don't count self-export) disappeared
8144  * osd can be released
8145  */
8146 static int osd_obd_disconnect(struct obd_export *exp)
8147 {
8148         struct obd_device *obd = exp->exp_obd;
8149         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8150         int rc, release = 0;
8151
8152         ENTRY;
8153
8154         /* Only disconnect the underlying layers on the final disconnect. */
8155         spin_lock(&osd->od_osfs_lock);
8156         osd->od_connects--;
8157         if (osd->od_connects == 0)
8158                 release = 1;
8159         spin_unlock(&osd->od_osfs_lock);
8160
8161         rc = class_disconnect(exp); /* bz 9811 */
8162
8163         if (rc == 0 && release)
8164                 class_manual_cleanup(obd);
8165         RETURN(rc);
8166 }
8167
8168 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
8169                        struct lu_device *dev)
8170 {
8171         struct osd_device *osd = osd_dev(dev);
8172         struct lr_server_data *lsd =
8173                         &osd->od_dt_dev.dd_lu_dev.ld_site->ls_tgt->lut_lsd;
8174         int result = 0;
8175
8176         ENTRY;
8177
8178         if (osd->od_quota_slave_md != NULL) {
8179                 /* set up quota slave objects for inode */
8180                 result = qsd_prepare(env, osd->od_quota_slave_md);
8181                 if (result != 0)
8182                         RETURN(result);
8183         }
8184
8185         if (osd->od_quota_slave_dt != NULL) {
8186                 /* set up quota slave objects for block */
8187                 result = qsd_prepare(env, osd->od_quota_slave_dt);
8188                 if (result != 0)
8189                         RETURN(result);
8190         }
8191
8192
8193         if (lsd->lsd_feature_incompat & OBD_COMPAT_OST) {
8194 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 52, 0)
8195                 if (lsd->lsd_feature_rocompat & OBD_ROCOMPAT_IDX_IN_IDIF) {
8196                         osd->od_index_in_idif = 1;
8197                 } else {
8198                         osd->od_index_in_idif = 0;
8199                         result = osd_register_proc_index_in_idif(osd);
8200                         if (result != 0)
8201                                 RETURN(result);
8202                 }
8203 #else
8204                 osd->od_index_in_idif = 1;
8205 #endif
8206         }
8207
8208         result = osd_fid_init(env, osd);
8209
8210         RETURN(result);
8211 }
8212
8213 static int osd_fid_alloc(const struct lu_env *env, struct obd_export *exp,
8214                          struct lu_fid *fid, struct md_op_data *op_data)
8215 {
8216         struct osd_device *osd = osd_dev(exp->exp_obd->obd_lu_dev);
8217
8218         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
8219 }
8220
8221 static const struct lu_object_operations osd_lu_obj_ops = {
8222         .loo_object_init      = osd_object_init,
8223         .loo_object_delete    = osd_object_delete,
8224         .loo_object_release   = osd_object_release,
8225         .loo_object_free      = osd_object_free,
8226         .loo_object_print     = osd_object_print,
8227         .loo_object_invariant = osd_object_invariant
8228 };
8229
8230 const struct lu_device_operations osd_lu_ops = {
8231         .ldo_object_alloc      = osd_object_alloc,
8232         .ldo_process_config    = osd_process_config,
8233         .ldo_recovery_complete = osd_recovery_complete,
8234         .ldo_prepare           = osd_prepare,
8235 };
8236
8237 static const struct lu_device_type_operations osd_device_type_ops = {
8238         .ldto_init = osd_type_init,
8239         .ldto_fini = osd_type_fini,
8240
8241         .ldto_start = osd_type_start,
8242         .ldto_stop  = osd_type_stop,
8243
8244         .ldto_device_alloc = osd_device_alloc,
8245         .ldto_device_free  = osd_device_free,
8246
8247         .ldto_device_init = osd_device_init,
8248         .ldto_device_fini = osd_device_fini
8249 };
8250
8251 static struct lu_device_type osd_device_type = {
8252         .ldt_tags     = LU_DEVICE_DT,
8253         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
8254         .ldt_ops      = &osd_device_type_ops,
8255         .ldt_ctx_tags = LCT_LOCAL,
8256 };
8257
8258 static int osd_health_check(const struct lu_env *env, struct obd_device *obd)
8259 {
8260         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8261         struct super_block *sb = osd_sb(osd);
8262
8263         return (osd->od_mnt == NULL || sb->s_flags & MS_RDONLY);
8264 }
8265
8266 /*
8267  * lprocfs legacy support.
8268  */
8269 static struct obd_ops osd_obd_device_ops = {
8270         .o_owner = THIS_MODULE,
8271         .o_connect      = osd_obd_connect,
8272         .o_disconnect   = osd_obd_disconnect,
8273         .o_fid_alloc    = osd_fid_alloc,
8274         .o_health_check = osd_health_check,
8275 };
8276
8277 static int __init osd_init(void)
8278 {
8279         int rc;
8280
8281         CLASSERT(BH_DXLock < sizeof(((struct buffer_head *)0)->b_state) * 8);
8282 #if !defined(CONFIG_DEBUG_MUTEXES) && !defined(CONFIG_DEBUG_SPINLOCK)
8283         /* please, try to keep osd_thread_info smaller than a page */
8284         CLASSERT(sizeof(struct osd_thread_info) <= PAGE_SIZE);
8285 #endif
8286
8287         osd_oi_mod_init();
8288
8289         rc = lu_kmem_init(ldiskfs_caches);
8290         if (rc)
8291                 return rc;
8292
8293 #ifdef CONFIG_KALLSYMS
8294         priv_dev_set_rdonly = (void *)kallsyms_lookup_name("dev_set_rdonly");
8295         priv_dev_check_rdonly =
8296                 (void *)kallsyms_lookup_name("dev_check_rdonly");
8297 #endif
8298
8299         rc = class_register_type(&osd_obd_device_ops, NULL, true,
8300                                  lprocfs_osd_module_vars,
8301                                  LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
8302         if (rc)
8303                 lu_kmem_fini(ldiskfs_caches);
8304         return rc;
8305 }
8306
8307 static void __exit osd_exit(void)
8308 {
8309         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
8310         lu_kmem_fini(ldiskfs_caches);
8311 }
8312
8313 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
8314 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
8315 MODULE_VERSION(LUSTRE_VERSION_STRING);
8316 MODULE_LICENSE("GPL");
8317
8318 module_init(osd_init);
8319 module_exit(osd_exit);