Whamcloud - gitweb
LU-13181 o2ib: fix page mapping error
[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         struct osd_idmap_cache *oclb_oic;
940         int oclb_items;
941         bool oclb_found;
942 };
943
944 /**
945  * It is called internally by ->readdir() to filter out the
946  * local slave object's FID of the striped directory.
947  *
948  * \retval      1 found the local slave's FID
949  * \retval      0 continue to check next item
950  * \retval      -ve for failure
951  */
952 #ifdef HAVE_FILLDIR_USE_CTX
953 static int osd_stripe_dir_filldir(struct dir_context *buf,
954 #else
955 static int osd_stripe_dir_filldir(void *buf,
956 #endif
957                                   const char *name, int namelen,
958                                   loff_t offset, __u64 ino, unsigned int d_type)
959 {
960         struct osd_check_lmv_buf *oclb = (struct osd_check_lmv_buf *)buf;
961         struct osd_thread_info *oti = oclb->oclb_info;
962         struct lu_fid *fid = &oti->oti_fid3;
963         struct osd_inode_id *id = &oti->oti_id3;
964         struct osd_device *dev = oclb->oclb_dev;
965         struct osd_idmap_cache *oic = oclb->oclb_oic;
966         struct inode *inode;
967
968         oclb->oclb_items++;
969
970         if (name[0] == '.')
971                 return 0;
972
973         fid_zero(fid);
974         sscanf(name + 1, SFID, RFID(fid));
975         if (!fid_is_sane(fid))
976                 return 0;
977
978         if (osd_remote_fid(oti->oti_env, dev, fid))
979                 return 0;
980
981         osd_id_gen(id, ino, OSD_OII_NOGEN);
982         inode = osd_iget(oti, dev, id);
983         if (IS_ERR(inode))
984                 return PTR_ERR(inode);
985
986         iput(inode);
987         osd_add_oi_cache(oti, dev, id, fid);
988         oic->oic_fid = *fid;
989         oic->oic_lid = *id;
990         oic->oic_dev = dev;
991         osd_oii_insert(dev, oic, true);
992         oclb->oclb_found = true;
993
994         return 1;
995 }
996
997 /*
998  * When lookup item under striped directory, we need to locate the master
999  * MDT-object of the striped directory firstly, then the client will send
1000  * lookup (getattr_by_name) RPC to the MDT with some slave MDT-object's FID
1001  * and the item's name. If the system is restored from MDT file level backup,
1002  * then before the OI scrub completely built the OI files, the OI mappings of
1003  * the master MDT-object and slave MDT-object may be invalid. Usually, it is
1004  * not a problem for the master MDT-object. Because when locate the master
1005  * MDT-object, we will do name based lookup (for the striped directory itself)
1006  * firstly, during such process we can setup the correct OI mapping for the
1007  * master MDT-object. But it will be trouble for the slave MDT-object. Because
1008  * the client will not trigger name based lookup on the MDT to locate the slave
1009  * MDT-object before locating item under the striped directory, then when
1010  * osd_fid_lookup(), it will find that the OI mapping for the slave MDT-object
1011  * is invalid and does not know what the right OI mapping is, then the MDT has
1012  * to return -EINPROGRESS to the client to notify that the OI scrub is rebuiding
1013  * the OI file, related OI mapping is unknown yet, please try again later. And
1014  * then client will re-try the RPC again and again until related OI mapping has
1015  * been updated. That is quite inefficient.
1016  *
1017  * To resolve above trouble, we will handle it as the following two cases:
1018  *
1019  * 1) The slave MDT-object and the master MDT-object are on different MDTs.
1020  *    It is relative easy. Be as one of remote MDT-objects, the slave MDT-object
1021  *    is linked under /REMOTE_PARENT_DIR with the name of its FID string.
1022  *    We can locate the slave MDT-object via lookup the /REMOTE_PARENT_DIR
1023  *    directly. Please check osd_fid_lookup().
1024  *
1025  * 2) The slave MDT-object and the master MDT-object reside on the same MDT.
1026  *    Under such case, during lookup the master MDT-object, we will lookup the
1027  *    slave MDT-object via readdir against the master MDT-object, because the
1028  *    slave MDT-objects information are stored as sub-directories with the name
1029  *    "${FID}:${index}". Then when find the local slave MDT-object, its OI
1030  *    mapping will be recorded. Then subsequent osd_fid_lookup() will know
1031  *    the correct OI mapping for the slave MDT-object.
1032  */
1033 static int osd_check_lmv(struct osd_thread_info *oti, struct osd_device *dev,
1034                          struct inode *inode, struct osd_idmap_cache *oic)
1035 {
1036         struct lu_buf *buf = &oti->oti_big_buf;
1037         struct dentry *dentry = &oti->oti_obj_dentry;
1038         struct file *filp = &oti->oti_file;
1039         const struct file_operations *fops;
1040         struct lmv_mds_md_v1 *lmv1;
1041         struct osd_check_lmv_buf oclb = {
1042 #ifdef HAVE_DIR_CONTEXT
1043                 .ctx.actor = osd_stripe_dir_filldir,
1044 #endif
1045                 .oclb_info = oti,
1046                 .oclb_dev = dev,
1047                 .oclb_oic = oic,
1048                 .oclb_found = false,
1049         };
1050         int rc = 0;
1051
1052         ENTRY;
1053
1054 again:
1055         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMV, buf->lb_buf,
1056                              buf->lb_len);
1057         if (rc == -ERANGE) {
1058                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMV, NULL, 0);
1059                 if (rc > 0) {
1060                         lu_buf_realloc(buf, rc);
1061                         if (buf->lb_buf == NULL)
1062                                 GOTO(out, rc = -ENOMEM);
1063
1064                         goto again;
1065                 }
1066         }
1067
1068         if (unlikely(rc == 0 || rc == -ENODATA))
1069                 GOTO(out, rc = 0);
1070
1071         if (rc < 0)
1072                 GOTO(out, rc);
1073
1074         if (unlikely(buf->lb_buf == NULL)) {
1075                 lu_buf_realloc(buf, rc);
1076                 if (buf->lb_buf == NULL)
1077                         GOTO(out, rc = -ENOMEM);
1078
1079                 goto again;
1080         }
1081
1082         lmv1 = buf->lb_buf;
1083         if (le32_to_cpu(lmv1->lmv_magic) != LMV_MAGIC_V1)
1084                 GOTO(out, rc = 0);
1085
1086         fops = inode->i_fop;
1087         dentry->d_inode = inode;
1088         dentry->d_sb = inode->i_sb;
1089         filp->f_pos = 0;
1090         filp->f_path.dentry = dentry;
1091         filp->f_mode = FMODE_64BITHASH;
1092         filp->f_mapping = inode->i_mapping;
1093         filp->f_op = fops;
1094         filp->private_data = NULL;
1095         set_file_inode(filp, inode);
1096
1097         do {
1098                 oclb.oclb_items = 0;
1099 #ifdef HAVE_DIR_CONTEXT
1100                 oclb.ctx.pos = filp->f_pos;
1101 #ifdef HAVE_ITERATE_SHARED
1102                 rc = fops->iterate_shared(filp, &oclb.ctx);
1103 #else
1104                 rc = fops->iterate(filp, &oclb.ctx);
1105 #endif
1106                 filp->f_pos = oclb.ctx.pos;
1107 #else
1108                 rc = fops->readdir(filp, &oclb, osd_stripe_dir_filldir);
1109 #endif
1110         } while (rc >= 0 && oclb.oclb_items > 0 && !oclb.oclb_found &&
1111                  filp->f_pos != LDISKFS_HTREE_EOF_64BIT);
1112         fops->release(inode, filp);
1113
1114 out:
1115         if (rc < 0)
1116                 CDEBUG(D_LFSCK, "%s: fail to check LMV EA, inode = %lu/%u,"
1117                        DFID": rc = %d\n", osd_ino2name(inode),
1118                        inode->i_ino, inode->i_generation,
1119                        PFID(&oic->oic_fid), rc);
1120         else
1121                 rc = 0;
1122
1123         RETURN(rc);
1124 }
1125
1126 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
1127                           const struct lu_fid *fid,
1128                           const struct lu_object_conf *conf)
1129 {
1130         struct osd_thread_info *info;
1131         struct lu_device *ldev = obj->oo_dt.do_lu.lo_dev;
1132         struct osd_device *dev;
1133         struct osd_idmap_cache *oic;
1134         struct osd_inode_id *id;
1135         struct inode *inode = NULL;
1136         struct lustre_scrub *scrub;
1137         struct scrub_file *sf;
1138         __u32 flags = SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT | SS_AUTO_FULL;
1139         __u32 saved_ino;
1140         __u32 saved_gen;
1141         int result = 0;
1142         int rc1 = 0;
1143         bool remote = false;
1144         bool trusted = true;
1145         bool updated = false;
1146         bool checked = false;
1147
1148         ENTRY;
1149
1150         LINVRNT(osd_invariant(obj));
1151         LASSERT(obj->oo_inode == NULL);
1152         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID"\n", PFID(fid));
1153
1154         dev = osd_dev(ldev);
1155         scrub = &dev->od_scrub.os_scrub;
1156         sf = &scrub->os_file;
1157         info = osd_oti_get(env);
1158         LASSERT(info);
1159         oic = &info->oti_cache;
1160
1161         if (OBD_FAIL_CHECK(OBD_FAIL_SRV_ENOENT))
1162                 RETURN(-ENOENT);
1163
1164         /*
1165          * For the object is created as locking anchor, or for the object to
1166          * be created on disk. No need to osd_oi_lookup() at here because FID
1167          * shouldn't never be re-used, if it's really a duplicate FID from
1168          * unexpected reason, we should be able to detect it later by calling
1169          * do_create->osd_oi_insert().
1170          */
1171         if (conf && conf->loc_flags & LOC_F_NEW)
1172                 GOTO(out, result = 0);
1173
1174         /* Search order: 1. per-thread cache. */
1175         if (lu_fid_eq(fid, &oic->oic_fid) && likely(oic->oic_dev == dev)) {
1176                 id = &oic->oic_lid;
1177                 goto iget;
1178         }
1179
1180         id = &info->oti_id;
1181         if (!list_empty(&scrub->os_inconsistent_items)) {
1182                 /* Search order: 2. OI scrub pending list. */
1183                 result = osd_oii_lookup(dev, fid, id);
1184                 if (!result)
1185                         goto iget;
1186         }
1187
1188         /*
1189          * The OI mapping in the OI file can be updated by the OI scrub
1190          * when we locate the inode via FID. So it may be not trustable.
1191          */
1192         trusted = false;
1193
1194         /* Search order: 3. OI files. */
1195         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1196         if (result == -ENOENT) {
1197                 if (!(fid_is_norm(fid) || fid_is_igif(fid)) ||
1198                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
1199                     !ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
1200                                       sf->sf_oi_bitmap))
1201                         GOTO(out, result = 0);
1202
1203                 goto trigger;
1204         }
1205
1206         /* -ESTALE is returned if inode of OST object doesn't exist */
1207         if (result == -ESTALE &&
1208             fid_is_on_ost(info, dev, fid, OI_CHECK_FLD)) {
1209                 GOTO(out, result = 0);
1210         }
1211
1212         if (result)
1213                 GOTO(out, result);
1214
1215 iget:
1216         obj->oo_inode = NULL;
1217         /* for later passes through checks, not true on first pass */
1218         if (!IS_ERR_OR_NULL(inode))
1219                 iput(inode);
1220
1221         inode = osd_iget_check(info, dev, fid, id, trusted);
1222         if (!IS_ERR(inode)) {
1223                 obj->oo_inode = inode;
1224                 result = 0;
1225                 if (remote)
1226                         goto trigger;
1227
1228                 goto check_lma;
1229         }
1230
1231         result = PTR_ERR(inode);
1232         if (result == -ENOENT || result == -ESTALE)
1233                 GOTO(out, result = 0);
1234
1235         if (result != -EREMCHG)
1236                 GOTO(out, result);
1237
1238 trigger:
1239         /*
1240          * We still have chance to get the valid inode: for the
1241          * object which is referenced by remote name entry, the
1242          * object on the local MDT will be linked under the dir
1243          * of "/REMOTE_PARENT_DIR" with its FID string as name.
1244          *
1245          * We do not know whether the object for the given FID
1246          * is referenced by some remote name entry or not, and
1247          * especially for DNE II, a multiple-linked object may
1248          * have many name entries reside on many MDTs.
1249          *
1250          * To simplify the operation, OSD will not distinguish
1251          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
1252          * only happened for the RPC from other MDT during the
1253          * OI scrub, or for the client side RPC with FID only,
1254          * such as FID to path, or from old connected client.
1255          */
1256         if (!remote) {
1257                 rc1 = osd_lookup_in_remote_parent(info, dev, fid, id);
1258                 if (!rc1) {
1259                         remote = true;
1260                         trusted = true;
1261                         flags |= SS_AUTO_PARTIAL;
1262                         flags &= ~SS_AUTO_FULL;
1263                         goto iget;
1264                 }
1265         }
1266
1267         if (thread_is_running(&scrub->os_thread)) {
1268                 if (scrub->os_partial_scan && !scrub->os_in_join)
1269                         goto join;
1270
1271                 if (IS_ERR_OR_NULL(inode) || result)
1272                         GOTO(out, result = -EINPROGRESS);
1273
1274                 LASSERT(remote);
1275                 LASSERT(obj->oo_inode == inode);
1276
1277                 osd_add_oi_cache(info, dev, id, fid);
1278                 osd_oii_insert(dev, oic, true);
1279                 goto found;
1280         }
1281
1282         if (dev->od_auto_scrub_interval == AS_NEVER) {
1283                 if (!remote)
1284                         GOTO(out, result = -EREMCHG);
1285
1286                 LASSERT(!result);
1287                 LASSERT(obj->oo_inode == inode);
1288
1289                 osd_add_oi_cache(info, dev, id, fid);
1290                 goto found;
1291         }
1292
1293 join:
1294         rc1 = osd_scrub_start(env, dev, flags);
1295         LCONSOLE_WARN("%s: trigger OI scrub by RPC for the " DFID" with flags "
1296                       "0x%x, rc = %d\n", osd_name(dev), PFID(fid), flags, rc1);
1297         if (rc1 && rc1 != -EALREADY)
1298                 GOTO(out, result = -EREMCHG);
1299
1300         if (IS_ERR_OR_NULL(inode) || result)
1301                 GOTO(out, result = -EINPROGRESS);
1302
1303         LASSERT(remote);
1304         LASSERT(obj->oo_inode == inode);
1305
1306         osd_add_oi_cache(info, dev, id, fid);
1307         osd_oii_insert(dev, oic, true);
1308         goto found;
1309
1310 check_lma:
1311         checked = true;
1312         if (unlikely(obj->oo_header))
1313                 goto found;
1314
1315         result = osd_check_lma(env, obj);
1316         if (!result)
1317                 goto found;
1318
1319         LASSERTF(id->oii_ino == inode->i_ino &&
1320                  id->oii_gen == inode->i_generation,
1321                  "locate wrong inode for FID: "DFID", %u/%u => %ld/%u\n",
1322                  PFID(fid), id->oii_ino, id->oii_gen,
1323                  inode->i_ino, inode->i_generation);
1324
1325         saved_ino = inode->i_ino;
1326         saved_gen = inode->i_generation;
1327
1328         if (unlikely(result == -ENODATA)) {
1329                 /*
1330                  * If the OI scrub updated the OI mapping by race, it
1331                  * must be valid. Trust the inode that has no LMA EA.
1332                  */
1333                 if (updated)
1334                         goto found;
1335
1336                 result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1337                 if (!result) {
1338                         /*
1339                          * The OI mapping is still there, the inode is still
1340                          * valid. It is just becaues the inode has no LMA EA.
1341                          */
1342                         if (saved_ino == id->oii_ino &&
1343                             saved_gen == id->oii_gen)
1344                                 goto found;
1345
1346                         /*
1347                          * It is the OI scrub updated the OI mapping by race.
1348                          * The new OI mapping must be valid.
1349                          */
1350                         trusted = true;
1351                         updated = true;
1352                         goto iget;
1353                 }
1354
1355                 /*
1356                  * "result == -ENOENT" means that the OI mappinghas been
1357                  * removed by race, so the inode belongs to other object.
1358                  *
1359                  * Others error can be returned  directly.
1360                  */
1361                 if (result == -ENOENT) {
1362                         LASSERT(trusted);
1363
1364                         obj->oo_inode = NULL;
1365                         result = 0;
1366                 }
1367         }
1368
1369         if (result != -EREMCHG)
1370                 GOTO(out, result);
1371
1372         LASSERT(!updated);
1373
1374         /*
1375          * if two OST objects map to the same inode, and inode mode is
1376          * (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666), which means it's
1377          * reserved by precreate, and not written yet, in this case, don't
1378          * set inode for the object whose FID mismatch, so that it can create
1379          * inode and not block precreate.
1380          */
1381         if (fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) &&
1382             inode->i_mode == (S_IFREG | S_ISUID | S_ISGID | S_ISVTX | 0666)) {
1383                 obj->oo_inode = NULL;
1384                 GOTO(out, result = 0);
1385         }
1386
1387         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
1388         /*
1389          * "result == -ENOENT" means the cached OI mapping has been removed
1390          * from the OI file by race, above inode belongs to other object.
1391          */
1392         if (result == -ENOENT) {
1393                 LASSERT(trusted);
1394
1395                 obj->oo_inode = NULL;
1396                 GOTO(out, result = 0);
1397         }
1398
1399         if (result)
1400                 GOTO(out, result);
1401
1402         if (saved_ino == id->oii_ino && saved_gen == id->oii_gen) {
1403                 result = -EREMCHG;
1404                 goto trigger;
1405         }
1406
1407         /*
1408          * It is the OI scrub updated the OI mapping by race.
1409          * The new OI mapping must be valid.
1410          */
1411         trusted = true;
1412         updated = true;
1413         goto iget;
1414
1415 found:
1416         if (!checked) {
1417                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
1418                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
1419
1420                 result = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
1421                 if (!result) {
1422                         if (lma->lma_compat & LMAC_STRIPE_INFO &&
1423                             dev->od_is_ost)
1424                                 obj->oo_pfid_in_lma = 1;
1425                         if (unlikely(lma->lma_incompat & LMAI_REMOTE_PARENT) &&
1426                             !dev->od_is_ost)
1427                                 lu_object_set_agent_entry(&obj->oo_dt.do_lu);
1428                 } else if (result != -ENODATA) {
1429                         GOTO(out, result);
1430                 }
1431         }
1432
1433         obj->oo_compat_dot_created = 1;
1434         obj->oo_compat_dotdot_created = 1;
1435
1436         if (S_ISDIR(inode->i_mode) &&
1437             (flags & SS_AUTO_PARTIAL || sf->sf_status == SS_SCANNING))
1438                 osd_check_lmv(info, dev, inode, oic);
1439
1440         result = osd_attach_jinode(inode);
1441         if (result)
1442                 GOTO(out, result);
1443
1444         if (!ldiskfs_pdo)
1445                 GOTO(out, result = 0);
1446
1447         LASSERT(!obj->oo_hl_head);
1448         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1449
1450         GOTO(out, result = (!obj->oo_hl_head ? -ENOMEM : 0));
1451
1452 out:
1453         if (result || !obj->oo_inode) {
1454                 if (!IS_ERR_OR_NULL(inode))
1455                         iput(inode);
1456
1457                 obj->oo_inode = NULL;
1458                 if (trusted)
1459                         fid_zero(&oic->oic_fid);
1460         }
1461
1462         LINVRNT(osd_invariant(obj));
1463         return result;
1464 }
1465
1466 /*
1467  * Concurrency: shouldn't matter.
1468  */
1469 static void osd_object_init0(struct osd_object *obj)
1470 {
1471         LASSERT(obj->oo_inode != NULL);
1472         obj->oo_dt.do_body_ops = &osd_body_ops;
1473         obj->oo_dt.do_lu.lo_header->loh_attr |=
1474                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
1475 }
1476
1477 /*
1478  * Concurrency: no concurrent access is possible that early in object
1479  * life-cycle.
1480  */
1481 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
1482                            const struct lu_object_conf *conf)
1483 {
1484         struct osd_object *obj = osd_obj(l);
1485         int result;
1486
1487         LINVRNT(osd_invariant(obj));
1488
1489         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
1490                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
1491                 l->lo_header->loh_attr |= LOHA_EXISTS;
1492                 return 0;
1493         }
1494
1495         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
1496         obj->oo_dt.do_body_ops = &osd_body_ops_new;
1497         if (result == 0 && obj->oo_inode != NULL) {
1498                 struct osd_thread_info *oti = osd_oti_get(env);
1499                 struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
1500
1501                 osd_object_init0(obj);
1502                 if (unlikely(obj->oo_header))
1503                         return 0;
1504
1505                 result = osd_get_lma(oti, obj->oo_inode,
1506                                      &oti->oti_obj_dentry, loa);
1507                 if (!result) {
1508                         /*
1509                          * Convert LMAI flags to lustre LMA flags
1510                          * and cache it to oo_lma_flags
1511                          */
1512                         obj->oo_lma_flags =
1513                                 lma_to_lustre_flags(loa->loa_lma.lma_incompat);
1514                 } else if (result == -ENODATA) {
1515                         result = 0;
1516                 }
1517         }
1518
1519         LINVRNT(osd_invariant(obj));
1520         return result;
1521 }
1522
1523 /*
1524  * The first part of oxe_buf is xattr name, and is '\0' terminated.
1525  * The left part is for value, binary mode.
1526  */
1527 struct osd_xattr_entry {
1528         struct list_head        oxe_list;
1529         size_t                  oxe_len;
1530         size_t                  oxe_namelen;
1531         bool                    oxe_exist;
1532         struct rcu_head         oxe_rcu;
1533         char                    oxe_buf[0];
1534 };
1535
1536 static int osd_oxc_get(struct osd_object *obj, const char *name,
1537                        struct lu_buf *buf)
1538 {
1539         struct osd_xattr_entry *tmp;
1540         struct osd_xattr_entry *oxe = NULL;
1541         size_t namelen = strlen(name);
1542         int rc;
1543
1544         ENTRY;
1545
1546         rcu_read_lock();
1547         list_for_each_entry_rcu(tmp, &obj->oo_xattr_list, oxe_list) {
1548                 if (namelen == tmp->oxe_namelen &&
1549                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1550                         oxe = tmp;
1551                         break;
1552                 }
1553         }
1554
1555         if (oxe == NULL)
1556                 GOTO(out, rc = -ENOENT);
1557
1558         if (!oxe->oxe_exist)
1559                 GOTO(out, rc = -ENODATA);
1560
1561         /* vallen */
1562         rc = oxe->oxe_len - sizeof(*oxe) - oxe->oxe_namelen - 1;
1563         LASSERT(rc > 0);
1564
1565         if (buf->lb_buf == NULL)
1566                 GOTO(out, rc);
1567
1568         if (buf->lb_len < rc)
1569                 GOTO(out, rc = -ERANGE);
1570
1571         memcpy(buf->lb_buf, &oxe->oxe_buf[namelen + 1], rc);
1572         EXIT;
1573 out:
1574         rcu_read_unlock();
1575
1576         return rc;
1577 }
1578
1579 static void osd_oxc_free(struct rcu_head *head)
1580 {
1581         struct osd_xattr_entry *oxe;
1582
1583         oxe = container_of(head, struct osd_xattr_entry, oxe_rcu);
1584         OBD_FREE(oxe, oxe->oxe_len);
1585 }
1586
1587 static void osd_oxc_add(struct osd_object *obj, const char *name,
1588                         const char *buf, int buflen)
1589 {
1590         struct osd_xattr_entry *oxe;
1591         struct osd_xattr_entry *old = NULL;
1592         struct osd_xattr_entry *tmp;
1593         size_t namelen = strlen(name);
1594         size_t len = sizeof(*oxe) + namelen + 1 + buflen;
1595
1596         OBD_ALLOC(oxe, len);
1597         if (oxe == NULL)
1598                 return;
1599
1600         INIT_LIST_HEAD(&oxe->oxe_list);
1601         oxe->oxe_len = len;
1602         oxe->oxe_namelen = namelen;
1603         memcpy(oxe->oxe_buf, name, namelen);
1604         if (buflen > 0) {
1605                 LASSERT(buf != NULL);
1606                 memcpy(oxe->oxe_buf + namelen + 1, buf, buflen);
1607                 oxe->oxe_exist = true;
1608         } else {
1609                 oxe->oxe_exist = false;
1610         }
1611
1612         /* this should be rarely called, just remove old and add new */
1613         spin_lock(&obj->oo_guard);
1614         list_for_each_entry(tmp, &obj->oo_xattr_list, oxe_list) {
1615                 if (namelen == tmp->oxe_namelen &&
1616                     strncmp(name, tmp->oxe_buf, namelen) == 0) {
1617                         old = tmp;
1618                         break;
1619                 }
1620         }
1621         if (old != NULL) {
1622                 list_replace_rcu(&old->oxe_list, &oxe->oxe_list);
1623                 call_rcu(&old->oxe_rcu, osd_oxc_free);
1624         } else {
1625                 list_add_tail_rcu(&oxe->oxe_list, &obj->oo_xattr_list);
1626         }
1627         spin_unlock(&obj->oo_guard);
1628 }
1629
1630 static void osd_oxc_del(struct osd_object *obj, const char *name)
1631 {
1632         struct osd_xattr_entry *oxe;
1633         size_t namelen = strlen(name);
1634
1635         spin_lock(&obj->oo_guard);
1636         list_for_each_entry(oxe, &obj->oo_xattr_list, oxe_list) {
1637                 if (namelen == oxe->oxe_namelen &&
1638                     strncmp(name, oxe->oxe_buf, namelen) == 0) {
1639                         list_del_rcu(&oxe->oxe_list);
1640                         call_rcu(&oxe->oxe_rcu, osd_oxc_free);
1641                         break;
1642                 }
1643         }
1644         spin_unlock(&obj->oo_guard);
1645 }
1646
1647 static void osd_oxc_fini(struct osd_object *obj)
1648 {
1649         struct osd_xattr_entry *oxe, *next;
1650
1651         list_for_each_entry_safe(oxe, next, &obj->oo_xattr_list, oxe_list) {
1652                 list_del(&oxe->oxe_list);
1653                 OBD_FREE(oxe, oxe->oxe_len);
1654         }
1655 }
1656
1657 /*
1658  * Concurrency: no concurrent access is possible that late in object
1659  * life-cycle.
1660  */
1661 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
1662 {
1663         struct osd_object *obj = osd_obj(l);
1664         struct lu_object_header *h = obj->oo_header;
1665
1666         LINVRNT(osd_invariant(obj));
1667
1668         osd_oxc_fini(obj);
1669         dt_object_fini(&obj->oo_dt);
1670         if (obj->oo_hl_head != NULL)
1671                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1672         OBD_FREE_PTR(obj);
1673         if (unlikely(h)) {
1674                 lu_object_header_fini(h);
1675                 OBD_FREE_PTR(h);
1676         }
1677 }
1678
1679 /*
1680  * Concurrency: no concurrent access is possible that late in object
1681  * life-cycle.
1682  */
1683 static void osd_index_fini(struct osd_object *o)
1684 {
1685         struct iam_container *bag;
1686
1687         if (o->oo_dir != NULL) {
1688                 bag = &o->oo_dir->od_container;
1689                 if (o->oo_inode != NULL) {
1690                         if (bag->ic_object == o->oo_inode)
1691                                 iam_container_fini(bag);
1692                 }
1693                 OBD_FREE_PTR(o->oo_dir);
1694                 o->oo_dir = NULL;
1695         }
1696 }
1697
1698 /*
1699  * Concurrency: no concurrent access is possible that late in object
1700  * life-cycle (for all existing callers, that is. New callers have to provide
1701  * their own locking.)
1702  */
1703 static int osd_inode_unlinked(const struct inode *inode)
1704 {
1705         return inode->i_nlink == 0;
1706 }
1707
1708 enum {
1709         OSD_TXN_OI_DELETE_CREDITS    = 20,
1710         OSD_TXN_INODE_DELETE_CREDITS = 20
1711 };
1712
1713 /*
1714  * Journal
1715  */
1716
1717 #if OSD_THANDLE_STATS
1718 /**
1719  * Set time when the handle is allocated
1720  */
1721 static void osd_th_alloced(struct osd_thandle *oth)
1722 {
1723         oth->oth_alloced = ktime_get();
1724 }
1725
1726 /**
1727  * Set time when the handle started
1728  */
1729 static void osd_th_started(struct osd_thandle *oth)
1730 {
1731         oth->oth_started = ktime_get();
1732 }
1733
1734 /**
1735  * Check whether the we deal with this handle for too long.
1736  */
1737 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
1738                                 ktime_t alloced, ktime_t started,
1739                                 ktime_t closed)
1740 {
1741         ktime_t now = ktime_get();
1742
1743         LASSERT(dev != NULL);
1744
1745         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
1746                             ktime_us_delta(started, alloced));
1747         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
1748                             ktime_us_delta(closed, started));
1749         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
1750                             ktime_us_delta(now, closed));
1751
1752         if (ktime_before(ktime_add_ns(alloced, 30 * NSEC_PER_SEC), now)) {
1753                 CWARN("transaction handle %p was open for too long: now %lld, alloced %lld, started %lld, closed %lld\n",
1754                                 oth, now, alloced, started, closed);
1755                 libcfs_debug_dumpstack(NULL);
1756         }
1757 }
1758
1759 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
1760 {                                                                       \
1761         ktime_t __closed = ktime_get();                                 \
1762         ktime_t __alloced = oth->oth_alloced;                           \
1763         ktime_t __started = oth->oth_started;                           \
1764                                                                         \
1765         expr;                                                           \
1766         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
1767 }
1768
1769 #else /* OSD_THANDLE_STATS */
1770
1771 #define osd_th_alloced(h)                  do {} while(0)
1772 #define osd_th_started(h)                  do {} while(0)
1773 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
1774
1775 #endif /* OSD_THANDLE_STATS */
1776
1777 /*
1778  * Concurrency: doesn't access mutable data.
1779  */
1780 static int osd_param_is_not_sane(const struct osd_device *dev,
1781                                  const struct thandle *th)
1782 {
1783         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
1784
1785         return oh->ot_credits > osd_transaction_size(dev);
1786 }
1787
1788 /*
1789  * Concurrency: shouldn't matter.
1790  */
1791 static void osd_trans_commit_cb(struct super_block *sb,
1792                                 struct ldiskfs_journal_cb_entry *jcb, int error)
1793 {
1794         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
1795         struct thandle *th = &oh->ot_super;
1796         struct lu_device *lud = &th->th_dev->dd_lu_dev;
1797         struct dt_txn_commit_cb *dcb, *tmp;
1798
1799         LASSERT(oh->ot_handle == NULL);
1800
1801         if (error)
1802                 CERROR("transaction @0x%p commit error: %d\n", th, error);
1803
1804         /* call per-transaction callbacks if any */
1805         list_for_each_entry_safe(dcb, tmp, &oh->ot_commit_dcb_list,
1806                                  dcb_linkage) {
1807                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1808                          "commit callback entry: magic=%x name='%s'\n",
1809                          dcb->dcb_magic, dcb->dcb_name);
1810                 list_del_init(&dcb->dcb_linkage);
1811                 dcb->dcb_func(NULL, th, dcb, error);
1812         }
1813
1814         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
1815         lu_device_put(lud);
1816         th->th_dev = NULL;
1817
1818         OBD_FREE_PTR(oh);
1819 }
1820
1821 #ifndef HAVE_SB_START_WRITE
1822 # define sb_start_write(sb) do {} while (0)
1823 # define sb_end_write(sb) do {} while (0)
1824 #endif
1825
1826 static struct thandle *osd_trans_create(const struct lu_env *env,
1827                                         struct dt_device *d)
1828 {
1829         struct osd_thread_info *oti = osd_oti_get(env);
1830         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1831         struct osd_thandle *oh;
1832         struct thandle *th;
1833
1834         ENTRY;
1835
1836         if (d->dd_rdonly) {
1837                 CERROR("%s: someone try to start transaction under "
1838                        "readonly mode, should be disabled.\n",
1839                        osd_name(osd_dt_dev(d)));
1840                 dump_stack();
1841                 RETURN(ERR_PTR(-EROFS));
1842         }
1843
1844         /* on pending IO in this thread should left from prev. request */
1845         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
1846
1847         sb_start_write(osd_sb(osd_dt_dev(d)));
1848
1849         OBD_ALLOC_GFP(oh, sizeof(*oh), GFP_NOFS);
1850         if (!oh) {
1851                 sb_end_write(osd_sb(osd_dt_dev(d)));
1852                 RETURN(ERR_PTR(-ENOMEM));
1853         }
1854
1855         oh->ot_quota_trans = &oti->oti_quota_trans;
1856         memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
1857         th = &oh->ot_super;
1858         th->th_dev = d;
1859         th->th_result = 0;
1860         oh->ot_credits = 0;
1861         INIT_LIST_HEAD(&oh->ot_commit_dcb_list);
1862         INIT_LIST_HEAD(&oh->ot_stop_dcb_list);
1863         INIT_LIST_HEAD(&oh->ot_trunc_locks);
1864         osd_th_alloced(oh);
1865
1866         memset(oti->oti_declare_ops, 0,
1867                sizeof(oti->oti_declare_ops));
1868         memset(oti->oti_declare_ops_cred, 0,
1869                sizeof(oti->oti_declare_ops_cred));
1870         memset(oti->oti_declare_ops_used, 0,
1871                sizeof(oti->oti_declare_ops_used));
1872
1873         oti->oti_ins_cache_depth++;
1874
1875         RETURN(th);
1876 }
1877
1878 void osd_trans_dump_creds(const struct lu_env *env, struct thandle *th)
1879 {
1880         struct osd_thread_info *oti = osd_oti_get(env);
1881         struct osd_thandle *oh;
1882
1883         oh = container_of0(th, struct osd_thandle, ot_super);
1884         LASSERT(oh != NULL);
1885
1886         CWARN("  create: %u/%u/%u, destroy: %u/%u/%u\n",
1887               oti->oti_declare_ops[OSD_OT_CREATE],
1888               oti->oti_declare_ops_cred[OSD_OT_CREATE],
1889               oti->oti_declare_ops_used[OSD_OT_CREATE],
1890               oti->oti_declare_ops[OSD_OT_DESTROY],
1891               oti->oti_declare_ops_cred[OSD_OT_DESTROY],
1892               oti->oti_declare_ops_used[OSD_OT_DESTROY]);
1893         CWARN("  attr_set: %u/%u/%u, xattr_set: %u/%u/%u\n",
1894               oti->oti_declare_ops[OSD_OT_ATTR_SET],
1895               oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1896               oti->oti_declare_ops_used[OSD_OT_ATTR_SET],
1897               oti->oti_declare_ops[OSD_OT_XATTR_SET],
1898               oti->oti_declare_ops_cred[OSD_OT_XATTR_SET],
1899               oti->oti_declare_ops_used[OSD_OT_XATTR_SET]);
1900         CWARN("  write: %u/%u/%u, punch: %u/%u/%u, quota %u/%u/%u\n",
1901               oti->oti_declare_ops[OSD_OT_WRITE],
1902               oti->oti_declare_ops_cred[OSD_OT_WRITE],
1903               oti->oti_declare_ops_used[OSD_OT_WRITE],
1904               oti->oti_declare_ops[OSD_OT_PUNCH],
1905               oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1906               oti->oti_declare_ops_used[OSD_OT_PUNCH],
1907               oti->oti_declare_ops[OSD_OT_QUOTA],
1908               oti->oti_declare_ops_cred[OSD_OT_QUOTA],
1909               oti->oti_declare_ops_used[OSD_OT_QUOTA]);
1910         CWARN("  insert: %u/%u/%u, delete: %u/%u/%u\n",
1911               oti->oti_declare_ops[OSD_OT_INSERT],
1912               oti->oti_declare_ops_cred[OSD_OT_INSERT],
1913               oti->oti_declare_ops_used[OSD_OT_INSERT],
1914               oti->oti_declare_ops[OSD_OT_DELETE],
1915               oti->oti_declare_ops_cred[OSD_OT_DELETE],
1916               oti->oti_declare_ops_used[OSD_OT_DELETE]);
1917         CWARN("  ref_add: %u/%u/%u, ref_del: %u/%u/%u\n",
1918               oti->oti_declare_ops[OSD_OT_REF_ADD],
1919               oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1920               oti->oti_declare_ops_used[OSD_OT_REF_ADD],
1921               oti->oti_declare_ops[OSD_OT_REF_DEL],
1922               oti->oti_declare_ops_cred[OSD_OT_REF_DEL],
1923               oti->oti_declare_ops_used[OSD_OT_REF_DEL]);
1924 }
1925
1926 /*
1927  * Concurrency: shouldn't matter.
1928  */
1929 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
1930                            struct thandle *th)
1931 {
1932         struct osd_thread_info *oti = osd_oti_get(env);
1933         struct osd_device *dev = osd_dt_dev(d);
1934         handle_t *jh;
1935         struct osd_thandle *oh;
1936         int rc;
1937
1938         ENTRY;
1939
1940         LASSERT(current->journal_info == NULL);
1941
1942         oh = container_of0(th, struct osd_thandle, ot_super);
1943         LASSERT(oh != NULL);
1944         LASSERT(oh->ot_handle == NULL);
1945
1946         rc = dt_txn_hook_start(env, d, th);
1947         if (rc != 0)
1948                 GOTO(out, rc);
1949
1950         if (unlikely(osd_param_is_not_sane(dev, th))) {
1951                 static unsigned long last_printed;
1952                 static int last_credits;
1953
1954                 /*
1955                  * don't make noise on a tiny testing systems
1956                  * actual credits misuse will be caught anyway
1957                  */
1958                 if (last_credits != oh->ot_credits &&
1959                     time_after(jiffies, last_printed +
1960                                msecs_to_jiffies(60 * MSEC_PER_SEC)) &&
1961                     osd_transaction_size(dev) > 512) {
1962                         CWARN("%s: credits %u > trans_max %u\n", osd_name(dev),
1963                               oh->ot_credits, osd_transaction_size(dev));
1964                         osd_trans_dump_creds(env, th);
1965                         libcfs_debug_dumpstack(NULL);
1966                         last_credits = oh->ot_credits;
1967                         last_printed = jiffies;
1968                 }
1969                 /*
1970                  * XXX Limit the credits to 'max_transaction_buffers', and
1971                  *     let the underlying filesystem to catch the error if
1972                  *     we really need so many credits.
1973                  *
1974                  *     This should be removed when we can calculate the
1975                  *     credits precisely.
1976                  */
1977                 oh->ot_credits = osd_transaction_size(dev);
1978         } else if (ldiskfs_track_declares_assert != 0) {
1979                 /*
1980                  * reserve few credits to prevent an assertion in JBD
1981                  * our debugging mechanism will be able to detected
1982                  * overuse. this can help to debug single-update
1983                  * transactions
1984                  */
1985                 oh->ot_credits += 10;
1986                 if (unlikely(osd_param_is_not_sane(dev, th)))
1987                         oh->ot_credits = osd_transaction_size(dev);
1988         }
1989
1990         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_TXN_START))
1991                 GOTO(out, rc = -EIO);
1992
1993         /*
1994          * XXX temporary stuff. Some abstraction layer should
1995          * be used.
1996          */
1997         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
1998         osd_th_started(oh);
1999         if (!IS_ERR(jh)) {
2000                 oh->ot_handle = jh;
2001                 LASSERT(oti->oti_txns == 0);
2002
2003                 lu_device_get(&d->dd_lu_dev);
2004                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
2005                               "osd-tx", th);
2006                 oti->oti_txns++;
2007                 rc = 0;
2008         } else {
2009                 rc = PTR_ERR(jh);
2010         }
2011 out:
2012         RETURN(rc);
2013 }
2014
2015 static int osd_seq_exists(const struct lu_env *env,
2016                           struct osd_device *osd, u64 seq)
2017 {
2018         struct lu_seq_range *range = &osd_oti_get(env)->oti_seq_range;
2019         struct seq_server_site *ss = osd_seq_site(osd);
2020         int rc;
2021
2022         ENTRY;
2023
2024         LASSERT(ss != NULL);
2025         LASSERT(ss->ss_server_fld != NULL);
2026
2027         rc = osd_fld_lookup(env, osd, seq, range);
2028         if (rc != 0) {
2029                 if (rc != -ENOENT)
2030                         CERROR("%s: can't lookup FLD sequence %#llx: rc = %d\n",
2031                                osd_name(osd), seq, rc);
2032                 RETURN(0);
2033         }
2034
2035         RETURN(ss->ss_node_id == range->lsr_index);
2036 }
2037
2038 static void osd_trans_stop_cb(struct osd_thandle *oth, int result)
2039 {
2040         struct dt_txn_commit_cb *dcb;
2041         struct dt_txn_commit_cb *tmp;
2042
2043         /* call per-transaction stop callbacks if any */
2044         list_for_each_entry_safe(dcb, tmp, &oth->ot_stop_dcb_list,
2045                                  dcb_linkage) {
2046                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
2047                          "commit callback entry: magic=%x name='%s'\n",
2048                          dcb->dcb_magic, dcb->dcb_name);
2049                 list_del_init(&dcb->dcb_linkage);
2050                 dcb->dcb_func(NULL, &oth->ot_super, dcb, result);
2051         }
2052 }
2053
2054 /*
2055  * Concurrency: shouldn't matter.
2056  */
2057 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
2058                           struct thandle *th)
2059 {
2060         struct osd_thread_info *oti = osd_oti_get(env);
2061         struct osd_thandle *oh;
2062         struct osd_iobuf *iobuf = &oti->oti_iobuf;
2063         struct osd_device *osd = osd_dt_dev(th->th_dev);
2064         struct qsd_instance *qsd = osd_def_qsd(osd);
2065         struct lquota_trans *qtrans;
2066         struct list_head truncates = LIST_HEAD_INIT(truncates);
2067         int rc = 0, remove_agents = 0;
2068
2069         ENTRY;
2070
2071         oh = container_of0(th, struct osd_thandle, ot_super);
2072
2073         remove_agents = oh->ot_remove_agents;
2074
2075         qtrans = oh->ot_quota_trans;
2076         oh->ot_quota_trans = NULL;
2077
2078         /* move locks to local list, stop tx, execute truncates */
2079         list_splice(&oh->ot_trunc_locks, &truncates);
2080
2081         if (oh->ot_handle != NULL) {
2082                 int rc2;
2083
2084                 handle_t *hdl = oh->ot_handle;
2085
2086                 /*
2087                  * add commit callback
2088                  * notice we don't do this in osd_trans_start()
2089                  * as underlying transaction can change during truncate
2090                  */
2091                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
2092                                              &oh->ot_jcb);
2093
2094                 LASSERT(oti->oti_txns == 1);
2095                 oti->oti_txns--;
2096
2097                 rc = dt_txn_hook_stop(env, th);
2098                 if (rc != 0)
2099                         CERROR("%s: failed in transaction hook: rc = %d\n",
2100                                osd_name(osd), rc);
2101
2102                 osd_trans_stop_cb(oh, rc);
2103                 /* hook functions might modify th_sync */
2104                 hdl->h_sync = th->th_sync;
2105
2106                 oh->ot_handle = NULL;
2107                 OSD_CHECK_SLOW_TH(oh, osd, rc2 = ldiskfs_journal_stop(hdl));
2108                 if (rc2 != 0)
2109                         CERROR("%s: failed to stop transaction: rc = %d\n",
2110                                osd_name(osd), rc2);
2111                 if (!rc)
2112                         rc = rc2;
2113
2114                 osd_process_truncates(&truncates);
2115         } else {
2116                 osd_trans_stop_cb(oh, th->th_result);
2117                 OBD_FREE_PTR(oh);
2118         }
2119
2120         osd_trunc_unlock_all(&truncates);
2121
2122         /* inform the quota slave device that the transaction is stopping */
2123         qsd_op_end(env, qsd, qtrans);
2124
2125         /*
2126          * as we want IO to journal and data IO be concurrent, we don't block
2127          * awaiting data IO completion in osd_do_bio(), instead we wait here
2128          * once transaction is submitted to the journal. all reqular requests
2129          * don't do direct IO (except read/write), thus this wait_event becomes
2130          * no-op for them.
2131          *
2132          * IMPORTANT: we have to wait till any IO submited by the thread is
2133          * completed otherwise iobuf may be corrupted by different request
2134          */
2135         wait_event(iobuf->dr_wait,
2136                        atomic_read(&iobuf->dr_numreqs) == 0);
2137         osd_fini_iobuf(osd, iobuf);
2138         if (!rc)
2139                 rc = iobuf->dr_error;
2140
2141         if (unlikely(remove_agents != 0))
2142                 osd_process_scheduled_agent_removals(env, osd);
2143
2144         LASSERT(oti->oti_ins_cache_depth > 0);
2145         oti->oti_ins_cache_depth--;
2146         /* reset OI cache for safety */
2147         if (oti->oti_ins_cache_depth == 0)
2148                 oti->oti_ins_cache_used = 0;
2149
2150         sb_end_write(osd_sb(osd));
2151
2152         RETURN(rc);
2153 }
2154
2155 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
2156 {
2157         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
2158                                                ot_super);
2159
2160         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
2161         LASSERT(&dcb->dcb_func != NULL);
2162         if (dcb->dcb_flags & DCB_TRANS_STOP)
2163                 list_add(&dcb->dcb_linkage, &oh->ot_stop_dcb_list);
2164         else
2165                 list_add(&dcb->dcb_linkage, &oh->ot_commit_dcb_list);
2166
2167         return 0;
2168 }
2169
2170 /*
2171  * Called just before object is freed. Releases all resources except for
2172  * object itself (that is released by osd_object_free()).
2173  *
2174  * Concurrency: no concurrent access is possible that late in object
2175  * life-cycle.
2176  */
2177 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
2178 {
2179         struct osd_object *obj = osd_obj(l);
2180         struct qsd_instance *qsd = osd_def_qsd(osd_obj2dev(obj));
2181         struct inode *inode = obj->oo_inode;
2182         __u64 projid;
2183         qid_t uid;
2184         qid_t gid;
2185
2186         LINVRNT(osd_invariant(obj));
2187
2188         /*
2189          * If object is unlinked remove fid->ino mapping from object index.
2190          */
2191
2192         osd_index_fini(obj);
2193
2194         if (!inode)
2195                 return;
2196
2197         if (osd_has_index(obj) &&  obj->oo_dt.do_index_ops == &osd_index_iam_ops)
2198                 ldiskfs_set_inode_flag(inode, LDISKFS_INODE_JOURNAL_DATA);
2199
2200         uid = i_uid_read(inode);
2201         gid = i_gid_read(inode);
2202         projid = i_projid_read(inode);
2203
2204         obj->oo_inode = NULL;
2205         iput(inode);
2206
2207         /* do not rebalance quota if the caller needs to release memory
2208          * otherwise qsd_refresh_usage() may went into a new ldiskfs
2209          * transaction and risk to deadlock - LU-12178 */
2210         if (current->flags & (PF_MEMALLOC | PF_KSWAPD))
2211                 return;
2212
2213         if (!obj->oo_header && qsd) {
2214                 struct osd_thread_info *info = osd_oti_get(env);
2215                 struct lquota_id_info *qi = &info->oti_qi;
2216
2217                 /* Release granted quota to master if necessary */
2218                 qi->lqi_id.qid_uid = uid;
2219                 qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
2220
2221                 qi->lqi_id.qid_uid = gid;
2222                 qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
2223
2224                 qi->lqi_id.qid_uid = projid;
2225                 qsd_op_adjust(env, qsd, &qi->lqi_id, PRJQUOTA);
2226         }
2227 }
2228
2229 /*
2230  * Concurrency: ->loo_object_release() is called under site spin-lock.
2231  */
2232 static void osd_object_release(const struct lu_env *env,
2233                                struct lu_object *l)
2234 {
2235         struct osd_object *o = osd_obj(l);
2236
2237         /*
2238          * nobody should be releasing a non-destroyed object with nlink=0
2239          * the API allows this, but ldiskfs doesn't like and then report
2240          * this inode as deleted
2241          */
2242         LASSERT(!(o->oo_destroyed == 0 && o->oo_inode &&
2243                   o->oo_inode->i_nlink == 0));
2244 }
2245
2246 /*
2247  * Concurrency: shouldn't matter.
2248  */
2249 static int osd_object_print(const struct lu_env *env, void *cookie,
2250                             lu_printer_t p, const struct lu_object *l)
2251 {
2252         struct osd_object *o = osd_obj(l);
2253         struct iam_descr *d;
2254
2255         if (o->oo_dir != NULL)
2256                 d = o->oo_dir->od_container.ic_descr;
2257         else
2258                 d = NULL;
2259         return (*p)(env, cookie,
2260                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
2261                     o, o->oo_inode,
2262                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
2263                     o->oo_inode ? o->oo_inode->i_generation : 0,
2264                     d ? d->id_ops->id_name : "plain");
2265 }
2266
2267 /*
2268  * Concurrency: shouldn't matter.
2269  */
2270 int osd_statfs(const struct lu_env *env, struct dt_device *d,
2271                 struct obd_statfs *sfs)
2272 {
2273         struct osd_device *osd = osd_dt_dev(d);
2274         struct super_block *sb = osd_sb(osd);
2275         struct kstatfs *ksfs;
2276         __u64 reserved;
2277         int result = 0;
2278
2279         if (unlikely(osd->od_mnt == NULL))
2280                 return -EINPROGRESS;
2281
2282         /* osd_lproc.c call this without env, allocate ksfs for that case */
2283         if (unlikely(env == NULL)) {
2284                 OBD_ALLOC_PTR(ksfs);
2285                 if (ksfs == NULL)
2286                         return -ENOMEM;
2287         } else {
2288                 ksfs = &osd_oti_get(env)->oti_ksfs;
2289         }
2290
2291         result = sb->s_op->statfs(sb->s_root, ksfs);
2292         if (result)
2293                 goto out;
2294
2295         statfs_pack(sfs, ksfs);
2296         if (unlikely(sb->s_flags & MS_RDONLY))
2297                 sfs->os_state |= OS_STATE_READONLY;
2298
2299         sfs->os_state |= osd->od_nonrotational ? OS_STATE_NONROT : 0;
2300
2301         if (ldiskfs_has_feature_extents(sb))
2302                 sfs->os_maxbytes = sb->s_maxbytes;
2303         else
2304                 sfs->os_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2305
2306         /*
2307          * Reserve some space so to avoid fragmenting the filesystem too much.
2308          * Fragmentation not only impacts performance, but can also increase
2309          * metadata overhead significantly, causing grant calculation to be
2310          * wrong.
2311          *
2312          * Reserve 0.78% of total space, at least 8MB for small filesystems.
2313          */
2314         CLASSERT(OSD_STATFS_RESERVED > LDISKFS_MAX_BLOCK_SIZE);
2315         reserved = OSD_STATFS_RESERVED >> sb->s_blocksize_bits;
2316         if (likely(sfs->os_blocks >= reserved << OSD_STATFS_RESERVED_SHIFT))
2317                 reserved = sfs->os_blocks >> OSD_STATFS_RESERVED_SHIFT;
2318
2319         sfs->os_blocks -= reserved;
2320         sfs->os_bfree  -= min(reserved, sfs->os_bfree);
2321         sfs->os_bavail -= min(reserved, sfs->os_bavail);
2322
2323 out:
2324         if (unlikely(env == NULL))
2325                 OBD_FREE_PTR(ksfs);
2326         return result;
2327 }
2328
2329 /**
2330  * Estimate space needed for file creations. We assume the largest filename
2331  * which is 2^64 - 1, hence a filename of 20 chars.
2332  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
2333  */
2334 #ifdef __LDISKFS_DIR_REC_LEN
2335 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
2336 #else
2337 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
2338 #endif
2339
2340 /*
2341  * Concurrency: doesn't access mutable data.
2342  */
2343 static void osd_conf_get(const struct lu_env *env,
2344                          const struct dt_device *dev,
2345                          struct dt_device_param *param)
2346 {
2347         struct osd_device *d = osd_dt_dev(dev);
2348         struct super_block *sb = osd_sb(d);
2349         struct blk_integrity *bi = bdev_get_integrity(sb->s_bdev);
2350         const char *name;
2351         int ea_overhead;
2352
2353         /*
2354          * XXX should be taken from not-yet-existing fs abstraction layer.
2355          */
2356         param->ddp_max_name_len = LDISKFS_NAME_LEN;
2357         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
2358         param->ddp_symlink_max  = sb->s_blocksize;
2359         param->ddp_mount_type   = LDD_MT_LDISKFS;
2360         if (ldiskfs_has_feature_extents(sb))
2361                 param->ddp_maxbytes = sb->s_maxbytes;
2362         else
2363                 param->ddp_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
2364         /*
2365          * inode are statically allocated, so per-inode space consumption
2366          * is the space consumed by the directory entry
2367          */
2368         param->ddp_inodespace     = PER_OBJ_USAGE;
2369         /*
2370          * EXT_INIT_MAX_LEN is the theoretical maximum extent size (32k blocks
2371          * is 128MB) which is unlikely to be hit in real life. Report a smaller
2372          * maximum length to not under-count the actual number of extents
2373          * needed for writing a file if there are sub-optimal block allocations.
2374          */
2375         param->ddp_max_extent_blks = EXT_INIT_MAX_LEN >> 1;
2376         /* worst-case extent insertion metadata overhead */
2377         param->ddp_extent_tax = 6 * LDISKFS_BLOCK_SIZE(sb);
2378         param->ddp_mntopts = 0;
2379         if (test_opt(sb, XATTR_USER))
2380                 param->ddp_mntopts |= MNTOPT_USERXATTR;
2381         if (test_opt(sb, POSIX_ACL))
2382                 param->ddp_mntopts |= MNTOPT_ACL;
2383
2384         /*
2385          * LOD might calculate the max stripe count based on max_ea_size,
2386          * so we need take account in the overhead as well,
2387          * xattr_header + magic + xattr_entry_head
2388          */
2389         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
2390                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
2391
2392 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
2393         if (ldiskfs_has_feature_ea_inode(sb))
2394                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
2395                                                                 ea_overhead;
2396         else
2397 #endif
2398                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
2399
2400         if (param->ddp_max_ea_size > OSD_MAX_EA_SIZE)
2401                 param->ddp_max_ea_size = OSD_MAX_EA_SIZE;
2402
2403         /*
2404          * Preferred RPC size for efficient disk IO.  4MB shows good
2405          * all-around performance for ldiskfs, but use bigalloc chunk size
2406          * by default if larger.
2407          */
2408 #if defined(LDISKFS_CLUSTER_SIZE)
2409         if (LDISKFS_CLUSTER_SIZE(sb) > DT_DEF_BRW_SIZE)
2410                 param->ddp_brw_size = LDISKFS_CLUSTER_SIZE(sb);
2411         else
2412 #endif
2413                 param->ddp_brw_size = DT_DEF_BRW_SIZE;
2414
2415         param->ddp_t10_cksum_type = 0;
2416         if (bi) {
2417                 unsigned short interval = blk_integrity_interval(bi);
2418                 name = blk_integrity_name(bi);
2419                 /*
2420                  * Expected values:
2421                  * T10-DIF-TYPE1-CRC
2422                  * T10-DIF-TYPE3-CRC
2423                  * T10-DIF-TYPE1-IP
2424                  * T10-DIF-TYPE3-IP
2425                  */
2426                 if (strncmp(name, "T10-DIF-TYPE",
2427                             sizeof("T10-DIF-TYPE") - 1) == 0) {
2428                         /* also skip "1/3-" at end */
2429                         const int type_off = sizeof("T10-DIF-TYPE.");
2430                         char type_number = name[type_off - 2];
2431
2432                         if (interval != 512 && interval != 4096) {
2433                                 CERROR("%s: unsupported T10PI sector size %u\n",
2434                                        d->od_svname, interval);
2435                         } else if (type_number != '1' && type_number != '3') {
2436                                 CERROR("%s: unsupported T10PI type %s\n",
2437                                        d->od_svname, name);
2438                         } else if (strcmp(name + type_off, "CRC") == 0) {
2439                                 d->od_t10_type = type_number == '1' ?
2440                                         OSD_T10_TYPE1_CRC : OSD_T10_TYPE3_CRC;
2441                                 param->ddp_t10_cksum_type = interval == 512 ?
2442                                         OBD_CKSUM_T10CRC512 :
2443                                         OBD_CKSUM_T10CRC4K;
2444                         } else if (strcmp(name + type_off, "IP") == 0) {
2445                                 d->od_t10_type = type_number == '1' ?
2446                                         OSD_T10_TYPE1_IP : OSD_T10_TYPE3_IP;
2447                                 param->ddp_t10_cksum_type = interval == 512 ?
2448                                         OBD_CKSUM_T10IP512 :
2449                                         OBD_CKSUM_T10IP4K;
2450                         } else {
2451                                 CERROR("%s: unsupported checksum type of "
2452                                        "T10PI type '%s'",
2453                                        d->od_svname, name);
2454                         }
2455
2456                 } else {
2457                         CERROR("%s: unsupported T10PI type '%s'",
2458                                d->od_svname, name);
2459                 }
2460         }
2461 }
2462
2463 static struct super_block *osd_mnt_sb_get(const struct dt_device *d)
2464 {
2465         return osd_sb(osd_dt_dev(d));
2466 }
2467
2468 /*
2469  * Concurrency: shouldn't matter.
2470  */
2471 static int osd_sync(const struct lu_env *env, struct dt_device *d)
2472 {
2473         int rc;
2474         struct super_block *s = osd_sb(osd_dt_dev(d));
2475         ENTRY;
2476
2477         down_read(&s->s_umount);
2478         rc = s->s_op->sync_fs(s, 1);
2479         up_read(&s->s_umount);
2480
2481         CDEBUG(D_CACHE, "%s: synced OSD: rc = %d\n", osd_dt_dev(d)->od_svname,
2482                rc);
2483
2484         return rc;
2485 }
2486
2487 /**
2488  * Start commit for OSD device.
2489  *
2490  * An implementation of dt_commit_async method for OSD device.
2491  * Asychronously starts underlayng fs sync and thereby a transaction
2492  * commit.
2493  *
2494  * \param env environment
2495  * \param d dt device
2496  *
2497  * \see dt_device_operations
2498  */
2499 static int osd_commit_async(const struct lu_env *env,
2500                             struct dt_device *d)
2501 {
2502         struct super_block *s = osd_sb(osd_dt_dev(d));
2503         int rc;
2504
2505         ENTRY;
2506
2507         CDEBUG(D_HA, "%s: async commit OSD\n", osd_dt_dev(d)->od_svname);
2508         down_read(&s->s_umount);
2509         rc = s->s_op->sync_fs(s, 0);
2510         up_read(&s->s_umount);
2511
2512         RETURN(rc);
2513 }
2514
2515 /* Our own copy of the set readonly functions if present, or NU if not. */
2516 static int (*priv_dev_set_rdonly)(struct block_device *bdev);
2517 static int (*priv_dev_check_rdonly)(struct block_device *bdev);
2518 /* static int (*priv_dev_clear_rdonly)(struct block_device *bdev); */
2519
2520 /*
2521  * Concurrency: shouldn't matter.
2522  */
2523 static int osd_ro(const struct lu_env *env, struct dt_device *d)
2524 {
2525         struct super_block *sb = osd_sb(osd_dt_dev(d));
2526         struct block_device *dev = sb->s_bdev;
2527         int rc = -EOPNOTSUPP;
2528
2529         ENTRY;
2530
2531         if (priv_dev_set_rdonly) {
2532                 struct block_device *jdev = LDISKFS_SB(sb)->journal_bdev;
2533
2534                 rc = 0;
2535                 CERROR("*** setting %s read-only ***\n",
2536                        osd_dt_dev(d)->od_svname);
2537
2538                 if (sb->s_op->freeze_fs) {
2539                         rc = sb->s_op->freeze_fs(sb);
2540                         if (rc)
2541                                 goto out;
2542                 }
2543
2544                 if (jdev && (jdev != dev)) {
2545                         CDEBUG(D_IOCTL | D_HA, "set journal dev %lx rdonly\n",
2546                                (long)jdev);
2547                         priv_dev_set_rdonly(jdev);
2548                 }
2549                 CDEBUG(D_IOCTL | D_HA, "set dev %lx rdonly\n", (long)dev);
2550                 priv_dev_set_rdonly(dev);
2551
2552                 if (sb->s_op->unfreeze_fs)
2553                         sb->s_op->unfreeze_fs(sb);
2554         }
2555
2556 out:
2557         if (rc)
2558                 CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
2559                        osd_dt_dev(d)->od_svname, (long)dev, rc);
2560
2561         RETURN(rc);
2562 }
2563
2564 /**
2565  * Note: we do not count into QUOTA here.
2566  * If we mount with --data_journal we may need more.
2567  */
2568 const int osd_dto_credits_noquota[DTO_NR] = {
2569         /**
2570          * Insert.
2571          * INDEX_EXTRA_TRANS_BLOCKS(8) +
2572          * SINGLEDATA_TRANS_BLOCKS(8)
2573          * XXX Note: maybe iam need more, since iam have more level than
2574          *           EXT3 htree.
2575          */
2576         [DTO_INDEX_INSERT]  = 16,
2577         /**
2578          * Delete
2579          * just modify a single entry, probably merge few within a block
2580          */
2581         [DTO_INDEX_DELETE]  = 1,
2582         /**
2583          * Used for OI scrub
2584          */
2585         [DTO_INDEX_UPDATE]  = 16,
2586         /**
2587          * 4(inode, inode bits, groups, GDT)
2588          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
2589          */
2590         [DTO_OBJECT_CREATE] = 4,
2591         /**
2592          * 4(inode, inode bits, groups, GDT)
2593          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
2594          */
2595         [DTO_OBJECT_DELETE] = 4,
2596         /**
2597          * Attr set credits (inode)
2598          */
2599         [DTO_ATTR_SET_BASE] = 1,
2600         /**
2601          * Xattr set. The same as xattr of EXT3.
2602          * DATA_TRANS_BLOCKS(14)
2603          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
2604          * are also counted in. Do not know why?
2605          */
2606         [DTO_XATTR_SET]     = 14,
2607         /**
2608          * credits for inode change during write.
2609          */
2610         [DTO_WRITE_BASE]    = 3,
2611         /**
2612          * credits for single block write.
2613          */
2614         [DTO_WRITE_BLOCK]   = 14,
2615         /**
2616          * Attr set credits for chown.
2617          * This is extra credits for setattr, and it is null without quota
2618          */
2619         [DTO_ATTR_SET_CHOWN] = 0
2620 };
2621
2622 static const struct dt_device_operations osd_dt_ops = {
2623         .dt_root_get       = osd_root_get,
2624         .dt_statfs         = osd_statfs,
2625         .dt_trans_create   = osd_trans_create,
2626         .dt_trans_start    = osd_trans_start,
2627         .dt_trans_stop     = osd_trans_stop,
2628         .dt_trans_cb_add   = osd_trans_cb_add,
2629         .dt_conf_get       = osd_conf_get,
2630         .dt_mnt_sb_get     = osd_mnt_sb_get,
2631         .dt_sync           = osd_sync,
2632         .dt_ro             = osd_ro,
2633         .dt_commit_async   = osd_commit_async,
2634 };
2635
2636 static void osd_read_lock(const struct lu_env *env, struct dt_object *dt,
2637                           unsigned int role)
2638 {
2639         struct osd_object *obj = osd_dt_obj(dt);
2640         struct osd_thread_info *oti = osd_oti_get(env);
2641
2642         LINVRNT(osd_invariant(obj));
2643
2644         LASSERT(obj->oo_owner != env);
2645         down_read_nested(&obj->oo_sem, role);
2646
2647         LASSERT(obj->oo_owner == NULL);
2648         oti->oti_r_locks++;
2649 }
2650
2651 static void osd_write_lock(const struct lu_env *env, struct dt_object *dt,
2652                            unsigned int role)
2653 {
2654         struct osd_object *obj = osd_dt_obj(dt);
2655         struct osd_thread_info *oti = osd_oti_get(env);
2656
2657         LINVRNT(osd_invariant(obj));
2658
2659         LASSERT(obj->oo_owner != env);
2660         down_write_nested(&obj->oo_sem, role);
2661
2662         LASSERT(obj->oo_owner == NULL);
2663         obj->oo_owner = env;
2664         oti->oti_w_locks++;
2665 }
2666
2667 static void osd_read_unlock(const struct lu_env *env, struct dt_object *dt)
2668 {
2669         struct osd_object *obj = osd_dt_obj(dt);
2670         struct osd_thread_info *oti = osd_oti_get(env);
2671
2672         LINVRNT(osd_invariant(obj));
2673
2674         LASSERT(oti->oti_r_locks > 0);
2675         oti->oti_r_locks--;
2676         up_read(&obj->oo_sem);
2677 }
2678
2679 static void osd_write_unlock(const struct lu_env *env, struct dt_object *dt)
2680 {
2681         struct osd_object *obj = osd_dt_obj(dt);
2682         struct osd_thread_info *oti = osd_oti_get(env);
2683
2684         LINVRNT(osd_invariant(obj));
2685
2686         LASSERT(obj->oo_owner == env);
2687         LASSERT(oti->oti_w_locks > 0);
2688         oti->oti_w_locks--;
2689         obj->oo_owner = NULL;
2690         up_write(&obj->oo_sem);
2691 }
2692
2693 static int osd_write_locked(const struct lu_env *env, struct dt_object *dt)
2694 {
2695         struct osd_object *obj = osd_dt_obj(dt);
2696
2697         LINVRNT(osd_invariant(obj));
2698
2699         return obj->oo_owner == env;
2700 }
2701
2702 #ifdef HAVE_INODE_TIMESPEC64
2703 static struct timespec64 osd_inode_time(const struct lu_env *env,
2704                                        struct inode *inode, __u64 seconds)
2705 #else
2706 static struct timespec osd_inode_time(const struct lu_env *env,
2707                                        struct inode *inode, __u64 seconds)
2708 #endif
2709 {
2710         struct osd_thread_info *oti = osd_oti_get(env);
2711         struct timespec *t = &oti->oti_time;
2712
2713         t->tv_sec = seconds;
2714         t->tv_nsec = 0;
2715         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
2716 #ifdef HAVE_INODE_TIMESPEC64
2717         return timespec_to_timespec64(*t);
2718 #else
2719         return *t;
2720 #endif
2721 }
2722
2723 static void osd_inode_getattr(const struct lu_env *env,
2724                               struct inode *inode, struct lu_attr *attr)
2725 {
2726         attr->la_valid  |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
2727                            LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
2728                            LA_PROJID | LA_FLAGS | LA_NLINK | LA_RDEV |
2729                            LA_BLKSIZE | LA_TYPE;
2730
2731         attr->la_atime = inode->i_atime.tv_sec;
2732         attr->la_mtime = inode->i_mtime.tv_sec;
2733         attr->la_ctime = inode->i_ctime.tv_sec;
2734         attr->la_mode    = inode->i_mode;
2735         attr->la_size    = i_size_read(inode);
2736         attr->la_blocks  = inode->i_blocks;
2737         attr->la_uid     = i_uid_read(inode);
2738         attr->la_gid     = i_gid_read(inode);
2739         attr->la_projid  = i_projid_read(inode);
2740         attr->la_flags   = ll_inode_to_ext_flags(inode->i_flags);
2741         attr->la_nlink   = inode->i_nlink;
2742         attr->la_rdev    = inode->i_rdev;
2743         attr->la_blksize = 1 << inode->i_blkbits;
2744         attr->la_blkbits = inode->i_blkbits;
2745         /*
2746          * Ext4 did not transfer inherit flags from raw inode
2747          * to inode flags, and ext4 internally test raw inode
2748          * @i_flags directly. Instead of patching ext4, we do it here.
2749          */
2750         if (LDISKFS_I(inode)->i_flags & LUSTRE_PROJINHERIT_FL)
2751                 attr->la_flags |= LUSTRE_PROJINHERIT_FL;
2752 }
2753
2754 static int osd_attr_get(const struct lu_env *env, struct dt_object *dt,
2755                         struct lu_attr *attr)
2756 {
2757         struct osd_object *obj = osd_dt_obj(dt);
2758
2759         if (unlikely(!dt_object_exists(dt)))
2760                 return -ENOENT;
2761         if (unlikely(obj->oo_destroyed))
2762                 return -ENOENT;
2763
2764         LASSERT(!dt_object_remote(dt));
2765         LINVRNT(osd_invariant(obj));
2766
2767         spin_lock(&obj->oo_guard);
2768         osd_inode_getattr(env, obj->oo_inode, attr);
2769         if (obj->oo_lma_flags & LUSTRE_ORPHAN_FL) {
2770                 attr->la_valid |= LA_FLAGS;
2771                 attr->la_flags |= LUSTRE_ORPHAN_FL;
2772         }
2773         spin_unlock(&obj->oo_guard);
2774
2775         return 0;
2776 }
2777
2778 static int osd_declare_attr_qid(const struct lu_env *env,
2779                                 struct osd_object *obj,
2780                                 struct osd_thandle *oh, long long bspace,
2781                                 qid_t old_id, qid_t new_id, bool enforce,
2782                                 unsigned int type, bool ignore_edquot)
2783 {
2784         int rc;
2785         struct osd_thread_info *info = osd_oti_get(env);
2786         struct lquota_id_info  *qi = &info->oti_qi;
2787
2788         qi->lqi_type = type;
2789         /* inode accounting */
2790         qi->lqi_is_blk = false;
2791
2792         /* one more inode for the new id ... */
2793         qi->lqi_id.qid_uid = new_id;
2794         qi->lqi_space      = 1;
2795         /* Reserve credits for the new id */
2796         rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
2797         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2798                 rc = 0;
2799         if (rc)
2800                 RETURN(rc);
2801
2802         /* and one less inode for the current id */
2803         qi->lqi_id.qid_uid = old_id;
2804         qi->lqi_space = -1;
2805         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2806         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2807                 rc = 0;
2808         if (rc)
2809                 RETURN(rc);
2810
2811         /* block accounting */
2812         qi->lqi_is_blk = true;
2813
2814         /* more blocks for the new id ... */
2815         qi->lqi_id.qid_uid = new_id;
2816         qi->lqi_space      = bspace;
2817         /*
2818          * Credits for the new uid has been reserved, re-use "obj"
2819          * to save credit reservation.
2820          */
2821         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2822         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2823                 rc = 0;
2824         if (rc)
2825                 RETURN(rc);
2826
2827         /* and finally less blocks for the current uid */
2828         qi->lqi_id.qid_uid = old_id;
2829         qi->lqi_space      = -bspace;
2830         rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2831         if (ignore_edquot && (rc == -EDQUOT || rc == -EINPROGRESS))
2832                 rc = 0;
2833
2834         RETURN(rc);
2835 }
2836
2837 static int osd_declare_attr_set(const struct lu_env *env,
2838                                 struct dt_object *dt,
2839                                 const struct lu_attr *attr,
2840                                 struct thandle *handle)
2841 {
2842         struct osd_thandle *oh;
2843         struct osd_object *obj;
2844         qid_t uid;
2845         qid_t gid;
2846         long long bspace;
2847         int rc = 0;
2848         bool enforce;
2849
2850         ENTRY;
2851
2852         LASSERT(dt != NULL);
2853         LASSERT(handle != NULL);
2854
2855         obj = osd_dt_obj(dt);
2856         LASSERT(osd_invariant(obj));
2857
2858         oh = container_of0(handle, struct osd_thandle, ot_super);
2859         LASSERT(oh->ot_handle == NULL);
2860
2861         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
2862                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2863
2864         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2865                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2866
2867         if (attr == NULL || obj->oo_inode == NULL)
2868                 RETURN(rc);
2869
2870         bspace   = obj->oo_inode->i_blocks << 9;
2871         bspace   = toqb(bspace);
2872
2873         /*
2874          * Changing ownership is always preformed by super user, it should not
2875          * fail with EDQUOT unless required explicitly.
2876          *
2877          * We still need to call the osd_declare_qid() to calculate the journal
2878          * credits for updating quota accounting files and to trigger quota
2879          * space adjustment once the operation is completed.
2880          */
2881         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
2882                 bool ignore_edquot = !(attr->la_flags & LUSTRE_SET_SYNC_FL);
2883
2884                 if (!ignore_edquot)
2885                         CDEBUG(D_QUOTA, "%s: enforce quota on UID %u, GID %u"
2886                                "(the quota space is %lld)\n",
2887                                obj->oo_inode->i_sb->s_id, attr->la_uid,
2888                                attr->la_gid, bspace);
2889
2890                 /* USERQUOTA */
2891                 uid = i_uid_read(obj->oo_inode);
2892                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
2893                 rc = osd_declare_attr_qid(env, obj, oh, bspace, uid,
2894                                           attr->la_uid, enforce, USRQUOTA,
2895                                           true);
2896                 if (rc)
2897                         RETURN(rc);
2898
2899                 gid = i_gid_read(obj->oo_inode);
2900                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
2901                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2902                                           i_gid_read(obj->oo_inode),
2903                                           attr->la_gid, enforce, GRPQUOTA,
2904                                           ignore_edquot);
2905                 if (rc)
2906                         RETURN(rc);
2907
2908         }
2909 #ifdef HAVE_PROJECT_QUOTA
2910         if (attr->la_valid & LA_PROJID) {
2911                 __u32 projid = i_projid_read(obj->oo_inode);
2912
2913                 enforce = (attr->la_valid & LA_PROJID) &&
2914                                         (attr->la_projid != projid);
2915                 rc = osd_declare_attr_qid(env, obj, oh, bspace,
2916                                           (qid_t)projid, (qid_t)attr->la_projid,
2917                                           enforce, PRJQUOTA, true);
2918                 if (rc)
2919                         RETURN(rc);
2920         }
2921 #endif
2922         RETURN(rc);
2923 }
2924
2925 static int osd_inode_setattr(const struct lu_env *env,
2926                              struct inode *inode, const struct lu_attr *attr)
2927 {
2928         __u64 bits = attr->la_valid;
2929
2930         /* Only allow set size for regular file */
2931         if (!S_ISREG(inode->i_mode))
2932                 bits &= ~(LA_SIZE | LA_BLOCKS);
2933
2934         if (bits == 0)
2935                 return 0;
2936
2937         if (bits & LA_ATIME)
2938                 inode->i_atime  = osd_inode_time(env, inode, attr->la_atime);
2939         if (bits & LA_CTIME)
2940                 inode->i_ctime  = osd_inode_time(env, inode, attr->la_ctime);
2941         if (bits & LA_MTIME)
2942                 inode->i_mtime  = osd_inode_time(env, inode, attr->la_mtime);
2943         if (bits & LA_SIZE) {
2944                 spin_lock(&inode->i_lock);
2945                 LDISKFS_I(inode)->i_disksize = attr->la_size;
2946                 i_size_write(inode, attr->la_size);
2947                 spin_unlock(&inode->i_lock);
2948         }
2949
2950         /*
2951          * OSD should not change "i_blocks" which is used by quota.
2952          * "i_blocks" should be changed by ldiskfs only.
2953          */
2954         if (bits & LA_MODE)
2955                 inode->i_mode = (inode->i_mode & S_IFMT) |
2956                                 (attr->la_mode & ~S_IFMT);
2957         if (bits & LA_UID)
2958                 i_uid_write(inode, attr->la_uid);
2959         if (bits & LA_GID)
2960                 i_gid_write(inode, attr->la_gid);
2961         if (bits & LA_PROJID)
2962                 i_projid_write(inode, attr->la_projid);
2963         if (bits & LA_NLINK)
2964                 set_nlink(inode, attr->la_nlink);
2965         if (bits & LA_RDEV)
2966                 inode->i_rdev = attr->la_rdev;
2967
2968         if (bits & LA_FLAGS) {
2969                 /* always keep S_NOCMTIME */
2970                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
2971                                  S_NOCMTIME;
2972                 /*
2973                  * Ext4 did not transfer inherit flags from
2974                  * @inode->i_flags to raw inode i_flags when writing
2975                  * flags, we do it explictly here.
2976                  */
2977                 if (attr->la_flags & LUSTRE_PROJINHERIT_FL)
2978                         LDISKFS_I(inode)->i_flags |= LUSTRE_PROJINHERIT_FL;
2979                 else
2980                         LDISKFS_I(inode)->i_flags &= ~LUSTRE_PROJINHERIT_FL;
2981         }
2982         return 0;
2983 }
2984
2985 #ifdef HAVE_PROJECT_QUOTA
2986 static int osd_transfer_project(struct inode *inode, __u32 projid,
2987                                 struct thandle *handle)
2988 {
2989         struct super_block *sb = inode->i_sb;
2990         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
2991         int err;
2992         kprojid_t kprojid;
2993         struct ldiskfs_iloc iloc;
2994         struct ldiskfs_inode *raw_inode;
2995         struct dquot *transfer_to[LDISKFS_MAXQUOTAS] = { };
2996
2997         if (!ldiskfs_has_feature_project(sb)) {
2998                 LASSERT(__kprojid_val(LDISKFS_I(inode)->i_projid)
2999                         == LDISKFS_DEF_PROJID);
3000                 if (projid != LDISKFS_DEF_PROJID)
3001                         return -EOPNOTSUPP;
3002                 else
3003                         return 0;
3004         }
3005
3006         if (LDISKFS_INODE_SIZE(sb) <= LDISKFS_GOOD_OLD_INODE_SIZE)
3007                 return -EOPNOTSUPP;
3008
3009         kprojid = make_kprojid(&init_user_ns, (projid_t)projid);
3010         if (projid_eq(kprojid, LDISKFS_I(inode)->i_projid))
3011                 return 0;
3012
3013         err = ldiskfs_get_inode_loc(inode, &iloc);
3014         if (err)
3015                 return err;
3016
3017         raw_inode = ldiskfs_raw_inode(&iloc);
3018         if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3019                 struct osd_thandle *oh =
3020                                 container_of0(handle, struct osd_thandle,
3021                                               ot_super);
3022                 /**
3023                  * try to expand inode size automatically.
3024                  */
3025                 ldiskfs_mark_inode_dirty(oh->ot_handle, inode);
3026                 if (!LDISKFS_FITS_IN_INODE(raw_inode, ei, i_projid)) {
3027                         err = -EOVERFLOW;
3028                         brelse(iloc.bh);
3029                         return err;
3030                 }
3031         }
3032         brelse(iloc.bh);
3033
3034         dquot_initialize(inode);
3035         transfer_to[PRJQUOTA] = dqget(sb, make_kqid_projid(kprojid));
3036         if (transfer_to[PRJQUOTA]) {
3037                 err = __dquot_transfer(inode, transfer_to);
3038                 dqput(transfer_to[PRJQUOTA]);
3039                 if (err)
3040                         return err;
3041         }
3042
3043         return err;
3044 }
3045 #endif
3046
3047 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr,
3048                               struct thandle *handle)
3049 {
3050         int rc;
3051
3052         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
3053             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
3054                 struct iattr iattr;
3055
3056                 ll_vfs_dq_init(inode);
3057                 iattr.ia_valid = 0;
3058                 if (attr->la_valid & LA_UID)
3059                         iattr.ia_valid |= ATTR_UID;
3060                 if (attr->la_valid & LA_GID)
3061                         iattr.ia_valid |= ATTR_GID;
3062                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
3063                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
3064
3065                 rc = ll_vfs_dq_transfer(inode, &iattr);
3066                 if (rc) {
3067                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
3068                                "enforcement enabled on the ldiskfs "
3069                                "filesystem?\n", inode->i_sb->s_id, rc);
3070                         return rc;
3071                 }
3072         }
3073
3074         /* Handle project id transfer here properly */
3075         if (attr->la_valid & LA_PROJID &&
3076             attr->la_projid != i_projid_read(inode)) {
3077 #ifdef HAVE_PROJECT_QUOTA
3078                 rc = osd_transfer_project(inode, attr->la_projid, handle);
3079 #else
3080                 rc = -ENOTSUPP;
3081 #endif
3082                 if (rc) {
3083                         CERROR("%s: quota transfer failed: rc = %d. Is project "
3084                                "enforcement enabled on the ldiskfs "
3085                                "filesystem?\n", inode->i_sb->s_id, rc);
3086                         return rc;
3087                 }
3088         }
3089         return 0;
3090 }
3091
3092 static int osd_attr_set(const struct lu_env *env,
3093                         struct dt_object *dt,
3094                         const struct lu_attr *attr,
3095                         struct thandle *handle)
3096 {
3097         struct osd_object *obj = osd_dt_obj(dt);
3098         struct inode *inode;
3099         int rc;
3100
3101         if (!dt_object_exists(dt))
3102                 return -ENOENT;
3103
3104         LASSERT(handle != NULL);
3105         LASSERT(!dt_object_remote(dt));
3106         LASSERT(osd_invariant(obj));
3107
3108         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
3109
3110         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING) &&
3111             !osd_obj2dev(obj)->od_is_ost) {
3112                 struct osd_thread_info *oti = osd_oti_get(env);
3113                 const struct lu_fid *fid0 = lu_object_fid(&dt->do_lu);
3114                 struct lu_fid *fid1 = &oti->oti_fid;
3115                 struct osd_inode_id *id = &oti->oti_id;
3116                 struct iam_path_descr *ipd;
3117                 struct iam_container *bag;
3118                 struct osd_thandle *oh;
3119                 int rc;
3120
3121                 fid_cpu_to_be(fid1, fid0);
3122                 memset(id, 1, sizeof(*id));
3123                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
3124                                   fid0)->oi_dir.od_container;
3125                 ipd = osd_idx_ipd_get(env, bag);
3126                 if (unlikely(ipd == NULL))
3127                         RETURN(-ENOMEM);
3128
3129                 oh = container_of0(handle, struct osd_thandle, ot_super);
3130                 rc = iam_update(oh->ot_handle, bag,
3131                                 (const struct iam_key *)fid1,
3132                                 (const struct iam_rec *)id, ipd);
3133                 osd_ipd_put(env, bag, ipd);
3134                 return(rc > 0 ? 0 : rc);
3135         }
3136
3137         inode = obj->oo_inode;
3138
3139         rc = osd_quota_transfer(inode, attr, handle);
3140         if (rc)
3141                 return rc;
3142
3143         spin_lock(&obj->oo_guard);
3144         rc = osd_inode_setattr(env, inode, attr);
3145         spin_unlock(&obj->oo_guard);
3146         if (rc != 0)
3147                 GOTO(out, rc);
3148
3149         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3150
3151         if (!(attr->la_valid & LA_FLAGS))
3152                 GOTO(out, rc);
3153
3154         /* Let's check if there are extra flags need to be set into LMA */
3155         if (attr->la_flags & LUSTRE_LMA_FL_MASKS) {
3156                 struct osd_thread_info *info = osd_oti_get(env);
3157                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
3158
3159                 LASSERT(!obj->oo_pfid_in_lma);
3160
3161                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
3162                                  &info->oti_ost_attrs);
3163                 if (rc)
3164                         GOTO(out, rc);
3165
3166                 lma->lma_incompat |=
3167                         lustre_to_lma_flags(attr->la_flags);
3168                 lustre_lma_swab(lma);
3169                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA,
3170                                      lma, sizeof(*lma), XATTR_REPLACE);
3171                 if (rc != 0) {
3172                         struct osd_device *osd = osd_obj2dev(obj);
3173
3174                         CWARN("%s: set "DFID" lma flags %u failed: rc = %d\n",
3175                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
3176                               lma->lma_incompat, rc);
3177                 } else {
3178                         obj->oo_lma_flags =
3179                                 attr->la_flags & LUSTRE_LMA_FL_MASKS;
3180                 }
3181                 osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
3182         }
3183 out:
3184         osd_trans_exec_check(env, handle, OSD_OT_ATTR_SET);
3185
3186         return rc;
3187 }
3188
3189 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
3190                                            struct osd_object *obj,
3191                                            const char *name, const int namelen)
3192 {
3193         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
3194 }
3195
3196 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
3197                       umode_t mode, struct dt_allocation_hint *hint,
3198                       struct thandle *th, struct lu_attr *attr)
3199 {
3200         int result;
3201         struct osd_device *osd = osd_obj2dev(obj);
3202         struct osd_thandle *oth;
3203         struct dt_object *parent = NULL;
3204         struct inode *inode;
3205         uid_t owner[2] = {0, 0};
3206
3207         if (attr->la_valid & LA_UID)
3208                 owner[0] = attr->la_uid;
3209         if (attr->la_valid & LA_GID)
3210                 owner[1] = attr->la_gid;
3211
3212         LINVRNT(osd_invariant(obj));
3213         LASSERT(obj->oo_inode == NULL);
3214         LASSERT(obj->oo_hl_head == NULL);
3215
3216         if (S_ISDIR(mode) && ldiskfs_pdo) {
3217                 obj->oo_hl_head =
3218                         ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
3219                 if (obj->oo_hl_head == NULL)
3220                         return -ENOMEM;
3221         }
3222
3223         oth = container_of(th, struct osd_thandle, ot_super);
3224         LASSERT(oth->ot_handle->h_transaction != NULL);
3225
3226         if (hint != NULL && hint->dah_parent != NULL &&
3227             !dt_object_remote(hint->dah_parent))
3228                 parent = hint->dah_parent;
3229
3230         inode = ldiskfs_create_inode(oth->ot_handle,
3231                                      parent ? osd_dt_obj(parent)->oo_inode :
3232                                               osd_sb(osd)->s_root->d_inode,
3233                                      mode, owner);
3234         if (!IS_ERR(inode)) {
3235                 /* Do not update file c/mtime in ldiskfs. */
3236                 inode->i_flags |= S_NOCMTIME;
3237
3238                 /*
3239                  * For new created object, it must be consistent,
3240                  * and it is unnecessary to scrub against it.
3241                  */
3242                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
3243
3244                 obj->oo_inode = inode;
3245                 result = 0;
3246         } else {
3247                 if (obj->oo_hl_head != NULL) {
3248                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
3249                         obj->oo_hl_head = NULL;
3250                 }
3251                 result = PTR_ERR(inode);
3252         }
3253         LINVRNT(osd_invariant(obj));
3254         return result;
3255 }
3256
3257 enum {
3258         OSD_NAME_LEN = 255
3259 };
3260
3261 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
3262                      struct lu_attr *attr,
3263                      struct dt_allocation_hint *hint,
3264                      struct dt_object_format *dof,
3265                      struct thandle *th)
3266 {
3267         int result;
3268         struct osd_thandle *oth;
3269         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX | S_ISGID));
3270
3271         LASSERT(S_ISDIR(attr->la_mode));
3272
3273         oth = container_of(th, struct osd_thandle, ot_super);
3274         LASSERT(oth->ot_handle->h_transaction != NULL);
3275         result = osd_mkfile(info, obj, mode, hint, th, attr);
3276
3277         return result;
3278 }
3279
3280 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
3281                         struct lu_attr *attr,
3282                         struct dt_allocation_hint *hint,
3283                         struct dt_object_format *dof,
3284                         struct thandle *th)
3285 {
3286         int result;
3287         struct osd_thandle *oth;
3288         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
3289
3290         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
3291
3292         LASSERT(S_ISREG(attr->la_mode));
3293
3294         oth = container_of(th, struct osd_thandle, ot_super);
3295         LASSERT(oth->ot_handle->h_transaction != NULL);
3296
3297         result = osd_mkfile(info, obj, mode, hint, th, attr);
3298         if (result == 0) {
3299                 LASSERT(obj->oo_inode != NULL);
3300                 if (feat->dif_flags & DT_IND_VARKEY)
3301                         result = iam_lvar_create(obj->oo_inode,
3302                                                  feat->dif_keysize_max,
3303                                                  feat->dif_ptrsize,
3304                                                  feat->dif_recsize_max,
3305                                                  oth->ot_handle);
3306                 else
3307                         result = iam_lfix_create(obj->oo_inode,
3308                                                  feat->dif_keysize_max,
3309                                                  feat->dif_ptrsize,
3310                                                  feat->dif_recsize_max,
3311                                                  oth->ot_handle);
3312         }
3313         return result;
3314 }
3315
3316 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
3317                      struct lu_attr *attr,
3318                      struct dt_allocation_hint *hint,
3319                      struct dt_object_format *dof,
3320                      struct thandle *th)
3321 {
3322         LASSERT(S_ISREG(attr->la_mode));
3323         return osd_mkfile(info, obj, (attr->la_mode &
3324                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3325                           attr);
3326 }
3327
3328 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
3329                      struct lu_attr *attr,
3330                      struct dt_allocation_hint *hint,
3331                      struct dt_object_format *dof,
3332                      struct thandle *th)
3333 {
3334         LASSERT(S_ISLNK(attr->la_mode));
3335         return osd_mkfile(info, obj, (attr->la_mode &
3336                          (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th,
3337                           attr);
3338 }
3339
3340 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
3341                      struct lu_attr *attr,
3342                      struct dt_allocation_hint *hint,
3343                      struct dt_object_format *dof,
3344                      struct thandle *th)
3345 {
3346         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
3347         int result;
3348
3349         LINVRNT(osd_invariant(obj));
3350         LASSERT(obj->oo_inode == NULL);
3351         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
3352                 S_ISFIFO(mode) || S_ISSOCK(mode));
3353
3354         result = osd_mkfile(info, obj, mode, hint, th, attr);
3355         if (result == 0) {
3356                 LASSERT(obj->oo_inode != NULL);
3357                 /*
3358                  * This inode should be marked dirty for i_rdev.  Currently
3359                  * that is done in the osd_attr_init().
3360                  */
3361                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
3362                                    attr->la_rdev);
3363         }
3364         LINVRNT(osd_invariant(obj));
3365         return result;
3366 }
3367
3368 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
3369                               struct lu_attr *,
3370                               struct dt_allocation_hint *hint,
3371                               struct dt_object_format *dof,
3372                               struct thandle *);
3373
3374 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
3375 {
3376         osd_obj_type_f result;
3377
3378         switch (type) {
3379         case DFT_DIR:
3380                 result = osd_mkdir;
3381                 break;
3382         case DFT_REGULAR:
3383                 result = osd_mkreg;
3384                 break;
3385         case DFT_SYM:
3386                 result = osd_mksym;
3387                 break;
3388         case DFT_NODE:
3389                 result = osd_mknod;
3390                 break;
3391         case DFT_INDEX:
3392                 result = osd_mk_index;
3393                 break;
3394
3395         default:
3396                 LBUG();
3397                 break;
3398         }
3399         return result;
3400 }
3401
3402
3403 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
3404                         struct dt_object *parent, struct dt_object *child,
3405                         umode_t child_mode)
3406 {
3407         LASSERT(ah);
3408
3409         ah->dah_parent = parent;
3410         ah->dah_mode = child_mode;
3411
3412         if (parent != NULL && !dt_object_remote(parent)) {
3413                 /* will help to find FID->ino at dt_insert("..") */
3414                 struct osd_object *pobj = osd_dt_obj(parent);
3415
3416                 osd_idc_find_and_init(env, osd_obj2dev(pobj), pobj);
3417         }
3418 }
3419
3420 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
3421                           struct lu_attr *attr, struct dt_object_format *dof,
3422                           struct thandle *handle)
3423 {
3424         struct inode *inode = obj->oo_inode;
3425         __u64 valid = attr->la_valid;
3426         int result;
3427
3428         attr->la_valid &= ~(LA_TYPE | LA_MODE);
3429
3430         if (dof->dof_type != DFT_NODE)
3431                 attr->la_valid &= ~LA_RDEV;
3432         if ((valid & LA_ATIME) && (attr->la_atime == inode->i_atime.tv_sec))
3433                 attr->la_valid &= ~LA_ATIME;
3434         if ((valid & LA_CTIME) && (attr->la_ctime == inode->i_ctime.tv_sec))
3435                 attr->la_valid &= ~LA_CTIME;
3436         if ((valid & LA_MTIME) && (attr->la_mtime == inode->i_mtime.tv_sec))
3437                 attr->la_valid &= ~LA_MTIME;
3438
3439         result = osd_quota_transfer(inode, attr, handle);
3440         if (result)
3441                 return;
3442
3443         if (attr->la_valid != 0) {
3444                 result = osd_inode_setattr(info->oti_env, inode, attr);
3445                 /*
3446                  * The osd_inode_setattr() should always succeed here.  The
3447                  * only error that could be returned is EDQUOT when we are
3448                  * trying to change the UID or GID of the inode. However, this
3449                  * should not happen since quota enforcement is no longer
3450                  * enabled on ldiskfs (lquota takes care of it).
3451                  */
3452                 LASSERTF(result == 0, "%d\n", result);
3453                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3454         }
3455
3456         attr->la_valid = valid;
3457 }
3458
3459 /**
3460  * Helper function for osd_create()
3461  *
3462  * \retval 0, on success
3463  */
3464 static int __osd_create(struct osd_thread_info *info, struct osd_object *obj,
3465                         struct lu_attr *attr, struct dt_allocation_hint *hint,
3466                         struct dt_object_format *dof, struct thandle *th)
3467 {
3468         int result;
3469         __u32 umask;
3470
3471         osd_trans_exec_op(info->oti_env, th, OSD_OT_CREATE);
3472
3473         /* we drop umask so that permissions we pass are not affected */
3474         umask = current->fs->umask;
3475         current->fs->umask = 0;
3476
3477         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
3478                                                   th);
3479         if (likely(obj->oo_inode != NULL)) {
3480                 LASSERT(obj->oo_inode->i_state & I_NEW);
3481
3482                 /*
3483                  * Unlock the inode before attr initialization to avoid
3484                  * unnecessary dqget operations. LU-6378
3485                  */
3486                 unlock_new_inode(obj->oo_inode);
3487         }
3488
3489         if (likely(result == 0)) {
3490                 osd_attr_init(info, obj, attr, dof, th);
3491                 osd_object_init0(obj);
3492         }
3493
3494         /* restore previous umask value */
3495         current->fs->umask = umask;
3496
3497         osd_trans_exec_check(info->oti_env, th, OSD_OT_CREATE);
3498
3499         return result;
3500 }
3501
3502 /**
3503  * Helper function for osd_create()
3504  *
3505  * \retval 0, on success
3506  */
3507 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
3508                            const struct lu_fid *fid, struct thandle *th)
3509 {
3510         struct osd_thread_info *info = osd_oti_get(env);
3511         struct osd_inode_id    *id   = &info->oti_id;
3512         struct osd_device      *osd  = osd_obj2dev(obj);
3513         struct osd_thandle     *oh;
3514         int rc;
3515
3516         LASSERT(obj->oo_inode != NULL);
3517
3518         oh = container_of0(th, struct osd_thandle, ot_super);
3519         LASSERT(oh->ot_handle);
3520         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3521
3522         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
3523         rc = osd_oi_insert(info, osd, fid, id, oh->ot_handle,
3524                            OI_CHECK_FLD, NULL);
3525         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP) && osd->od_is_ost) {
3526                 struct lu_fid next_fid = *fid;
3527
3528                 /* insert next object in advance, and map to the same inode */
3529                 next_fid.f_oid++;
3530                 if (next_fid.f_oid != 0) {
3531                         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3532                         osd_oi_insert(info, osd, &next_fid, id, oh->ot_handle,
3533                                       OI_CHECK_FLD, NULL);
3534                         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3535                 }
3536         }
3537
3538         osd_trans_exec_check(env, th, OSD_OT_INSERT);
3539
3540         return rc;
3541 }
3542
3543 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
3544                    u64 seq, struct lu_seq_range *range)
3545 {
3546         struct seq_server_site *ss = osd_seq_site(osd);
3547
3548         if (fid_seq_is_idif(seq)) {
3549                 fld_range_set_ost(range);
3550                 range->lsr_index = idif_ost_idx(seq);
3551                 return 0;
3552         }
3553
3554         if (!fid_seq_in_fldb(seq)) {
3555                 fld_range_set_mdt(range);
3556                 if (ss != NULL)
3557                         /*
3558                          * FIXME: If ss is NULL, it suppose not get lsr_index
3559                          * at all
3560                          */
3561                         range->lsr_index = ss->ss_node_id;
3562                 return 0;
3563         }
3564
3565         LASSERT(ss != NULL);
3566         fld_range_set_any(range);
3567         /* OSD will only do local fld lookup */
3568         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
3569 }
3570
3571 static int osd_declare_create(const struct lu_env *env, struct dt_object *dt,
3572                               struct lu_attr *attr,
3573                               struct dt_allocation_hint *hint,
3574                               struct dt_object_format *dof,
3575                               struct thandle *handle)
3576 {
3577         struct osd_thandle *oh;
3578         int rc;
3579
3580         ENTRY;
3581
3582         LASSERT(handle != NULL);
3583
3584         oh = container_of0(handle, struct osd_thandle, ot_super);
3585         LASSERT(oh->ot_handle == NULL);
3586
3587         /*
3588          * EA object consumes more credits than regular object: osd_mk_index
3589          * vs. osd_mkreg: osd_mk_index will create 2 blocks for root_node and
3590          * leaf_node, could involves the block, block bitmap, groups, GDT
3591          * change for each block, so add 4 * 2 credits in that case.
3592          */
3593         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
3594                              osd_dto_credits_noquota[DTO_OBJECT_CREATE] +
3595                              (dof->dof_type == DFT_INDEX) ? 4 * 2 : 0);
3596         /*
3597          * Reuse idle OI block may cause additional one OI block
3598          * to be changed.
3599          */
3600         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3601                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3602         if (CFS_FAIL_CHECK(OBD_FAIL_OSD_DUPLICATE_MAP))
3603                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3604                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
3605
3606         /* will help to find FID->ino mapping at dt_insert() */
3607         rc = osd_idc_find_and_init(env, osd_obj2dev(osd_dt_obj(dt)),
3608                                    osd_dt_obj(dt));
3609         if (rc != 0)
3610                 RETURN(rc);
3611
3612         if (!attr)
3613                 RETURN(0);
3614
3615         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid,
3616                                    attr->la_projid, 1, oh, osd_dt_obj(dt),
3617                                    NULL, OSD_QID_INODE);
3618         if (rc != 0)
3619                 RETURN(rc);
3620
3621         RETURN(rc);
3622 }
3623
3624 /**
3625  * Called to destroy on-disk representation of the object
3626  *
3627  * Concurrency: must be locked
3628  */
3629 static int osd_declare_destroy(const struct lu_env *env, struct dt_object *dt,
3630                                struct thandle *th)
3631 {
3632         struct osd_object *obj = osd_dt_obj(dt);
3633         struct inode *inode = obj->oo_inode;
3634         struct osd_thandle *oh;
3635         int rc;
3636
3637         ENTRY;
3638
3639         if (inode == NULL)
3640                 RETURN(-ENOENT);
3641
3642         oh = container_of0(th, struct osd_thandle, ot_super);
3643         LASSERT(oh->ot_handle == NULL);
3644
3645         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
3646                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
3647
3648         /* For removing agent entry */
3649         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu))
3650                 oh->ot_credits += osd_dto_credits_noquota[DTO_INDEX_DELETE];
3651
3652         /*
3653          * Recycle idle OI leaf may cause additional three OI blocks
3654          * to be changed.
3655          */
3656         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3657                 osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3658                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
3659         /* one less inode */
3660         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3661                                    i_projid_read(inode), -1, oh, obj, NULL,
3662                                    OSD_QID_INODE);
3663         if (rc)
3664                 RETURN(rc);
3665         /* data to be truncated */
3666         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3667                                    i_projid_read(inode), 0, oh, obj, NULL,
3668                                    OSD_QID_BLK);
3669         if (rc)
3670                 RETURN(rc);
3671
3672         /*
3673          * will help to find FID->ino when this object is being
3674          * added to PENDING
3675          */
3676         rc = osd_idc_find_and_init(env, osd_obj2dev(obj), obj);
3677
3678         RETURN(rc);
3679 }
3680
3681 static int osd_destroy(const struct lu_env *env, struct dt_object *dt,
3682                        struct thandle *th)
3683 {
3684         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
3685         struct osd_object *obj = osd_dt_obj(dt);
3686         struct inode *inode = obj->oo_inode;
3687         struct osd_device *osd = osd_obj2dev(obj);
3688         struct osd_thandle *oh;
3689         int result;
3690
3691         ENTRY;
3692
3693         oh = container_of0(th, struct osd_thandle, ot_super);
3694         LASSERT(oh->ot_handle);
3695         LASSERT(inode);
3696         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
3697
3698         if (unlikely(fid_is_acct(fid)))
3699                 RETURN(-EPERM);
3700
3701         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu)) {
3702                 result = osd_delete_from_remote_parent(env, osd, obj, oh, true);
3703                 if (result != 0)
3704                         CERROR("%s: remove agent entry "DFID": rc = %d\n",
3705                                osd_name(osd), PFID(fid), result);
3706         }
3707
3708         if (S_ISDIR(inode->i_mode)) {
3709                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1 ||
3710                         inode->i_nlink == 2);
3711
3712                 spin_lock(&obj->oo_guard);
3713                 clear_nlink(inode);
3714                 spin_unlock(&obj->oo_guard);
3715                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3716         }
3717
3718         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
3719
3720         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
3721
3722         if (!OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LOST_MDTOBJ2))
3723                 result = osd_oi_delete(osd_oti_get(env), osd, fid,
3724                                        oh->ot_handle, OI_CHECK_FLD);
3725
3726         osd_trans_exec_check(env, th, OSD_OT_DESTROY);
3727         /* XXX: add to ext3 orphan list */
3728         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
3729
3730         /* not needed in the cache anymore */
3731         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
3732         obj->oo_destroyed = 1;
3733
3734         RETURN(0);
3735 }
3736
3737 /**
3738  * Put the fid into lustre_mdt_attrs, and then place the structure
3739  * inode's ea. This fid should not be altered during the life time
3740  * of the inode.
3741  *
3742  * \retval +ve, on success
3743  * \retval -ve, on error
3744  *
3745  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
3746  */
3747 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
3748                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
3749 {
3750         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
3751         struct lustre_mdt_attrs *lma = &loa->loa_lma;
3752         int rc;
3753
3754         ENTRY;
3755
3756         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
3757                 RETURN(0);
3758
3759         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_OST_EA_FID_SET))
3760                 rc = -ENOMEM;
3761
3762         lustre_loa_init(loa, fid, compat, incompat);
3763         lustre_loa_swab(loa, false);
3764
3765         /*
3766          * For the OST device with 256 bytes inode size by default,
3767          * the PFID EA will be stored together with LMA EA to avoid
3768          * performance trouble. Otherwise the PFID EA can be stored
3769          * independently. LU-8998
3770          */
3771         if ((compat & LMAC_FID_ON_OST) &&
3772             LDISKFS_INODE_SIZE(inode->i_sb) <= 256)
3773                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3774                                      sizeof(*loa), XATTR_CREATE);
3775         else
3776                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3777                                      sizeof(*lma), XATTR_CREATE);
3778         /*
3779          * LMA may already exist, but we need to check that all the
3780          * desired compat/incompat flags have been added.
3781          */
3782         if (unlikely(rc == -EEXIST)) {
3783                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
3784                                      XATTR_NAME_LMA, (void *)loa, sizeof(*loa));
3785                 if (rc < 0)
3786                         RETURN(rc);
3787
3788                 if (rc < sizeof(*lma))
3789                         RETURN(-EINVAL);
3790
3791                 lustre_loa_swab(loa, true);
3792                 if (lu_fid_eq(fid, &lma->lma_self_fid) &&
3793                     ((compat == 0 && incompat == 0) ||
3794                      (!(~lma->lma_compat & compat) &&
3795                       !(~lma->lma_incompat & incompat))))
3796                         RETURN(0);
3797
3798                 lma->lma_self_fid = *fid;
3799                 lma->lma_compat |= compat;
3800                 lma->lma_incompat |= incompat;
3801                 if (rc == sizeof(*lma)) {
3802                         lustre_lma_swab(lma);
3803                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3804                                              sizeof(*lma), XATTR_REPLACE);
3805                 } else {
3806                         lustre_loa_swab(loa, false);
3807                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa,
3808                                              sizeof(*loa), XATTR_REPLACE);
3809                 }
3810         }
3811
3812         RETURN(rc);
3813 }
3814
3815 /**
3816  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
3817  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
3818  * To have compatilibility with 1.8 ldiskfs driver we need to have
3819  * magic number at start of fid data.
3820  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
3821  * its inmemory API.
3822  */
3823 static void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
3824                                          const struct lu_fid *fid)
3825 {
3826         if (!fid_is_namespace_visible(fid) ||
3827             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
3828                 param->edp_magic = 0;
3829                 return;
3830         }
3831
3832         param->edp_magic = LDISKFS_LUFID_MAGIC;
3833         param->edp_len =  sizeof(struct lu_fid) + 1;
3834         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
3835 }
3836
3837 /**
3838  * Try to read the fid from inode ea into dt_rec.
3839  *
3840  * \param fid object fid.
3841  *
3842  * \retval 0 on success
3843  */
3844 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
3845                           __u32 ino, struct lu_fid *fid,
3846                           struct osd_inode_id *id)
3847 {
3848         struct osd_thread_info *info  = osd_oti_get(env);
3849         struct inode *inode;
3850
3851         ENTRY;
3852
3853         osd_id_gen(id, ino, OSD_OII_NOGEN);
3854         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
3855         if (IS_ERR(inode))
3856                 RETURN(PTR_ERR(inode));
3857
3858         iput(inode);
3859         RETURN(0);
3860 }
3861
3862 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
3863                                         struct inode *dir,
3864                                         struct inode *parent_dir,
3865                                         const struct lu_fid *dot_fid,
3866                                         const struct lu_fid *dot_dot_fid,
3867                                         struct osd_thandle *oth)
3868 {
3869         struct ldiskfs_dentry_param *dot_ldp;
3870         struct ldiskfs_dentry_param *dot_dot_ldp;
3871         __u32 saved_nlink = dir->i_nlink;
3872         int rc;
3873
3874         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
3875         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
3876
3877         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3878         dot_ldp->edp_magic = 0;
3879
3880         rc = ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
3881                                     dir, dot_ldp, dot_dot_ldp);
3882         /*
3883          * The ldiskfs_add_dot_dotdot() may dir->i_nlink as 2, then
3884          * the subseqent ref_add() will increase the dir->i_nlink
3885          * as 3. That is incorrect for new created directory.
3886          *
3887          * It looks like hack, because we want to make the OSD API
3888          * to be order-independent for new created directory object
3889          * between dt_insert(..) and ref_add() operations.
3890          *
3891          * Here, we only restore the in-RAM dir-inode's nlink attr,
3892          * becuase if the nlink attr is not 2, then there will be
3893          * ref_add() called following the dt_insert(..), such call
3894          * will make both the in-RAM and on-disk dir-inode's nlink
3895          * attr to be set as 2. LU-7447
3896          */
3897         set_nlink(dir, saved_nlink);
3898         return rc;
3899 }
3900
3901 /**
3902  * Create an local agent inode for remote entry
3903  */
3904 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
3905                                                   struct osd_device *osd,
3906                                                   struct osd_object *pobj,
3907                                                   const struct lu_fid *fid,
3908                                                   __u32 type,
3909                                                   struct thandle *th)
3910 {
3911         struct osd_thread_info *info = osd_oti_get(env);
3912         struct inode *local;
3913         struct osd_thandle *oh;
3914         uid_t own[2] = {0, 0};
3915         int rc;
3916
3917         ENTRY;
3918
3919         LASSERT(th);
3920         oh = container_of(th, struct osd_thandle, ot_super);
3921         LASSERT(oh->ot_handle->h_transaction != NULL);
3922
3923         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, type, own);
3924         if (IS_ERR(local)) {
3925                 CERROR("%s: create local error %d\n", osd_name(osd),
3926                        (int)PTR_ERR(local));
3927                 RETURN(local);
3928         }
3929
3930         /*
3931          * restore i_gid in case S_ISGID is set, we will inherit S_ISGID and set
3932          * correct gid on remote file, not agent here
3933          */
3934         local->i_gid = current_fsgid();
3935         ldiskfs_set_inode_state(local, LDISKFS_STATE_LUSTRE_NOSCRUB);
3936
3937         /* e2fsck doesn't like empty symlinks.  Store remote FID as symlink.
3938          * That gives e2fsck something to look at and be happy, and allows
3939          * debugging if we need to determine where this symlink came from.
3940          */
3941         if (S_ISLNK(type)) {
3942                 CLASSERT(LDISKFS_N_BLOCKS * 4 >= FID_LEN + 1);
3943                 rc = snprintf((char *)LDISKFS_I(local)->i_data,
3944                               LDISKFS_N_BLOCKS * 4, DFID, PFID(fid));
3945
3946                 i_size_write(local, rc);
3947                 LDISKFS_I(local)->i_disksize = rc;
3948         }
3949         unlock_new_inode(local);
3950
3951         /* Agent inode should not have project ID */
3952 #ifdef  HAVE_PROJECT_QUOTA
3953         if (LDISKFS_I(pobj->oo_inode)->i_flags & LUSTRE_PROJINHERIT_FL &&
3954             i_projid_read(pobj->oo_inode) != 0) {
3955                 rc = osd_transfer_project(local, 0, th);
3956                 if (rc) {
3957                         CERROR("%s: quota transfer failed: rc = %d. Is project "
3958                                "quota enforcement enabled on the ldiskfs "
3959                                "filesystem?\n", local->i_sb->s_id, rc);
3960                         RETURN(ERR_PTR(rc));
3961                 }
3962         }
3963 #endif
3964         /* Set special LMA flag for local agent inode */
3965         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
3966         if (rc != 0) {
3967                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
3968                        osd_name(osd), PFID(fid), rc);
3969                 RETURN(ERR_PTR(rc));
3970         }
3971
3972         if (!S_ISDIR(type))
3973                 RETURN(local);
3974
3975         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
3976                                          lu_object_fid(&pobj->oo_dt.do_lu),
3977                                          fid, oh);
3978         if (rc != 0) {
3979                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
3980                         osd_name(osd), PFID(fid), rc);
3981                 RETURN(ERR_PTR(rc));
3982         }
3983
3984         RETURN(local);
3985 }
3986
3987 /**
3988  * when direntry is deleted, we have to take care of possible agent inode
3989  * referenced by that. unfortunately we can't do this at that point:
3990  * iget() within a running transaction leads to deadlock and we better do
3991  * not call that every delete declaration to save performance. so we put
3992  * a potention agent inode on a list and process that once the transaction
3993  * is over. Notice it's not any worse in terms of real orphans as regular
3994  * object destroy doesn't put inodes on the on-disk orphan list. this should
3995  * be addressed separately
3996  */
3997 static int osd_schedule_agent_inode_removal(const struct lu_env *env,
3998                                             struct osd_thandle *oh,
3999                                             __u32 ino)
4000 {
4001         struct osd_device *osd = osd_dt_dev(oh->ot_super.th_dev);
4002         struct osd_obj_orphan *oor;
4003
4004         OBD_ALLOC_PTR(oor);
4005         if (oor == NULL)
4006                 return -ENOMEM;
4007
4008         oor->oor_ino = ino;
4009         oor->oor_env = (struct lu_env *)env;
4010         spin_lock(&osd->od_osfs_lock);
4011         list_add(&oor->oor_list, &osd->od_orphan_list);
4012         spin_unlock(&osd->od_osfs_lock);
4013
4014         oh->ot_remove_agents = 1;
4015
4016         return 0;
4017
4018 }
4019
4020 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
4021                                                 struct osd_device *osd)
4022 {
4023         struct osd_thread_info *info = osd_oti_get(env);
4024         struct osd_obj_orphan *oor, *tmp;
4025         struct osd_inode_id id;
4026         struct list_head list;
4027         struct inode *inode;
4028         struct lu_fid fid;
4029         handle_t *jh;
4030         __u32 ino;
4031
4032         INIT_LIST_HEAD(&list);
4033
4034         spin_lock(&osd->od_osfs_lock);
4035         list_for_each_entry_safe(oor, tmp, &osd->od_orphan_list, oor_list) {
4036                 if (oor->oor_env == env) {
4037                         list_del(&oor->oor_list);
4038                         list_add(&oor->oor_list, &list);
4039                 }
4040         }
4041         spin_unlock(&osd->od_osfs_lock);
4042
4043         list_for_each_entry_safe(oor, tmp, &list, oor_list) {
4044
4045                 ino = oor->oor_ino;
4046
4047                 list_del(&oor->oor_list);
4048                 OBD_FREE_PTR(oor);
4049
4050                 osd_id_gen(&id, ino, OSD_OII_NOGEN);
4051                 inode = osd_iget_fid(info, osd, &id, &fid);
4052                 if (IS_ERR(inode))
4053                         continue;
4054
4055                 if (!osd_remote_fid(env, osd, &fid)) {
4056                         iput(inode);
4057                         continue;
4058                 }
4059
4060                 jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC, 1);
4061                 clear_nlink(inode);
4062                 mark_inode_dirty(inode);
4063                 ldiskfs_journal_stop(jh);
4064                 iput(inode);
4065         }
4066
4067         return 0;
4068 }
4069
4070 /**
4071  * OSD layer object create function for OST objects (b=11826).
4072  *
4073  * The FID is inserted into inode xattr here.
4074  *
4075  * \retval   0, on success
4076  * \retval -ve, on error
4077  */
4078 static int osd_create(const struct lu_env *env, struct dt_object *dt,
4079                       struct lu_attr *attr, struct dt_allocation_hint *hint,
4080                       struct dt_object_format *dof, struct thandle *th)
4081 {
4082         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4083         struct osd_object *obj = osd_dt_obj(dt);
4084         struct osd_thread_info *info = osd_oti_get(env);
4085         int result, on_ost = 0;
4086
4087         ENTRY;
4088
4089         if (dt_object_exists(dt))
4090                 RETURN(-EEXIST);
4091
4092         LINVRNT(osd_invariant(obj));
4093         LASSERT(!dt_object_remote(dt));
4094         LASSERT(osd_is_write_locked(env, obj));
4095         LASSERT(th != NULL);
4096
4097         if (unlikely(fid_is_acct(fid)))
4098                 /*
4099                  * Quota files can't be created from the kernel any more,
4100                  * 'tune2fs -O quota' will take care of creating them
4101                  */
4102                 RETURN(-EPERM);
4103
4104         result = __osd_create(info, obj, attr, hint, dof, th);
4105         if (result == 0) {
4106                 if (fid_is_idif(fid) &&
4107                     !osd_dev(dt->do_lu.lo_dev)->od_index_in_idif) {
4108                         struct lu_fid *tfid = &info->oti_fid;
4109                         struct ost_id *oi   = &info->oti_ostid;
4110
4111                         fid_to_ostid(fid, oi);
4112                         ostid_to_fid(tfid, oi, 0);
4113                         on_ost = 1;
4114                         result = osd_ea_fid_set(info, obj->oo_inode, tfid,
4115                                                 LMAC_FID_ON_OST, 0);
4116                 } else {
4117                         on_ost = fid_is_on_ost(info, osd_obj2dev(obj),
4118                                                fid, OI_CHECK_FLD);
4119                         result = osd_ea_fid_set(info, obj->oo_inode, fid,
4120                                                 on_ost ? LMAC_FID_ON_OST : 0,
4121                                                 0);
4122                 }
4123                 if (obj->oo_dt.do_body_ops == &osd_body_ops_new)
4124                         obj->oo_dt.do_body_ops = &osd_body_ops;
4125         }
4126
4127         if (!result && !CFS_FAIL_CHECK(OBD_FAIL_OSD_NO_OI_ENTRY))
4128                 result = __osd_oi_insert(env, obj, fid, th);
4129
4130         /*
4131          * a small optimization - dt_insert() isn't usually applied
4132          * to OST objects, so we don't need to cache OI mapping for
4133          * OST objects
4134          */
4135         if (result == 0 && on_ost == 0) {
4136                 struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4137
4138                 result = osd_idc_find_and_init(env, osd, obj);
4139                 LASSERT(result == 0);
4140         }
4141
4142         LASSERT(ergo(result == 0,
4143                      dt_object_exists(dt) && !dt_object_remote(dt)));
4144         LINVRNT(osd_invariant(obj));
4145         RETURN(result);
4146 }
4147
4148 static int osd_declare_ref_add(const struct lu_env *env, struct dt_object *dt,
4149                                struct thandle *handle)
4150 {
4151         struct osd_thandle *oh;
4152         int rc;
4153
4154         /* it's possible that object doesn't exist yet */
4155         LASSERT(handle != NULL);
4156
4157         oh = container_of0(handle, struct osd_thandle, ot_super);
4158         LASSERT(oh->ot_handle == NULL);
4159
4160         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
4161                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4162
4163         rc = osd_idc_find_and_init(env, osd_dev(dt->do_lu.lo_dev),
4164                                    osd_dt_obj(dt));
4165
4166         return rc;
4167 }
4168
4169 /*
4170  * Concurrency: @dt is write locked.
4171  */
4172 static int osd_ref_add(const struct lu_env *env, struct dt_object *dt,
4173                        struct thandle *th)
4174 {
4175         struct osd_object *obj = osd_dt_obj(dt);
4176         struct inode *inode = obj->oo_inode;
4177         struct osd_thandle *oh;
4178         int rc = 0;
4179
4180         if (!dt_object_exists(dt) || obj->oo_destroyed)
4181                 return -ENOENT;
4182
4183         LINVRNT(osd_invariant(obj));
4184         LASSERT(!dt_object_remote(dt));
4185         LASSERT(osd_is_write_locked(env, obj));
4186         LASSERT(th != NULL);
4187
4188         oh = container_of0(th, struct osd_thandle, ot_super);
4189         LASSERT(oh->ot_handle != NULL);
4190
4191         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
4192
4193         CDEBUG(D_INODE, DFID" increase nlink %d\n",
4194                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4195         /*
4196          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
4197          * (65000) subdirectories by storing "1" in i_nlink if the link count
4198          * would otherwise overflow. Directory tranversal tools understand
4199          * that (st_nlink == 1) indicates that the filesystem dose not track
4200          * hard links count on the directory, and will not abort subdirectory
4201          * scanning early once (st_nlink - 2) subdirs have been found.
4202          *
4203          * This also has to properly handle the case of inodes with nlink == 0
4204          * in case they are being linked into the PENDING directory
4205          */
4206         spin_lock(&obj->oo_guard);
4207         if (unlikely(inode->i_nlink == 0))
4208                 /* inc_nlink from 0 may cause WARN_ON */
4209                 set_nlink(inode, 1);
4210         else {
4211                 ldiskfs_inc_count(oh->ot_handle, inode);
4212                 if (!S_ISDIR(inode->i_mode))
4213                         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
4214         }
4215         spin_unlock(&obj->oo_guard);
4216
4217         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
4218         LINVRNT(osd_invariant(obj));
4219
4220         osd_trans_exec_check(env, th, OSD_OT_REF_ADD);
4221
4222         return rc;
4223 }
4224
4225 static int osd_declare_ref_del(const struct lu_env *env, struct dt_object *dt,
4226                                struct thandle *handle)
4227 {
4228         struct osd_thandle *oh;
4229
4230         if (!dt_object_exists(dt))
4231                 return -ENOENT;
4232
4233         LASSERT(!dt_object_remote(dt));
4234         LASSERT(handle != NULL);
4235
4236         oh = container_of0(handle, struct osd_thandle, ot_super);
4237         LASSERT(oh->ot_handle == NULL);
4238
4239         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
4240                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
4241
4242         return 0;
4243 }
4244
4245 /*
4246  * Concurrency: @dt is write locked.
4247  */
4248 static int osd_ref_del(const struct lu_env *env, struct dt_object *dt,
4249                        struct thandle *th)
4250 {
4251         struct osd_object *obj = osd_dt_obj(dt);
4252         struct inode *inode = obj->oo_inode;
4253         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
4254         struct osd_thandle *oh;
4255
4256         if (!dt_object_exists(dt))
4257                 return -ENOENT;
4258
4259         LINVRNT(osd_invariant(obj));
4260         LASSERT(!dt_object_remote(dt));
4261         LASSERT(osd_is_write_locked(env, obj));
4262         LASSERT(th != NULL);
4263
4264         oh = container_of0(th, struct osd_thandle, ot_super);
4265         LASSERT(oh->ot_handle != NULL);
4266
4267         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
4268
4269         spin_lock(&obj->oo_guard);
4270         /*
4271          * That can be result of upgrade from old Lustre version and
4272          * applied only to local files.  Just skip this ref_del call.
4273          * ext4_unlink() only treats this as a warning, don't LASSERT here.
4274          */
4275         if (inode->i_nlink == 0) {
4276                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
4277                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
4278                              ", maybe an upgraded file? (LU-3915)\n",
4279                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
4280                 spin_unlock(&obj->oo_guard);
4281                 return 0;
4282         }
4283
4284         CDEBUG(D_INODE, DFID" decrease nlink %d\n",
4285                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
4286
4287         ldiskfs_dec_count(oh->ot_handle, inode);
4288         spin_unlock(&obj->oo_guard);
4289
4290         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
4291         LINVRNT(osd_invariant(obj));
4292
4293         osd_trans_exec_check(env, th, OSD_OT_REF_DEL);
4294
4295         return 0;
4296 }
4297
4298 /*
4299  * Concurrency: @dt is read locked.
4300  */
4301 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
4302                          struct lu_buf *buf, const char *name)
4303 {
4304         struct osd_object      *obj    = osd_dt_obj(dt);
4305         struct inode           *inode  = obj->oo_inode;
4306         struct osd_thread_info *info   = osd_oti_get(env);
4307         struct dentry          *dentry = &info->oti_obj_dentry;
4308         bool cache_xattr = false;
4309         int rc;
4310
4311         LASSERT(buf);
4312
4313         /* version get is not real XATTR but uses xattr API */
4314         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4315                 dt_obj_version_t *ver = buf->lb_buf;
4316
4317                 /*
4318                  * for version we are just using xattr API but change inode
4319                  * field instead
4320                  */
4321                 if (buf->lb_len == 0)
4322                         return sizeof(dt_obj_version_t);
4323
4324                 if (buf->lb_len < sizeof(dt_obj_version_t))
4325                         return -ERANGE;
4326
4327                 CDEBUG(D_INODE, "Get version %#llx for inode %lu\n",
4328                        LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4329
4330                 *ver = LDISKFS_I(inode)->i_fs_version;
4331
4332                 return sizeof(dt_obj_version_t);
4333         }
4334
4335         if (!dt_object_exists(dt))
4336                 return -ENOENT;
4337
4338         LASSERT(!dt_object_remote(dt));
4339         LASSERT(inode->i_op != NULL);
4340 #ifdef HAVE_IOP_XATTR
4341         LASSERT(inode->i_op->getxattr != NULL);
4342 #endif
4343
4344         if (strcmp(name, XATTR_NAME_LOV) == 0 ||
4345             strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0)
4346                 cache_xattr = true;
4347
4348         if (cache_xattr) {
4349                 rc = osd_oxc_get(obj, name, buf);
4350                 if (rc != -ENOENT)
4351                         return rc;
4352         }
4353
4354         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4355                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4356                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4357                 struct filter_fid *ff;
4358                 struct ost_layout *ol;
4359
4360                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4361                 if (rc)
4362                         return rc;
4363
4364                 LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4365
4366                 rc = sizeof(*ff);
4367                 if (buf->lb_len == 0 || !buf->lb_buf)
4368                         return rc;
4369
4370                 if (buf->lb_len < rc)
4371                         return -ERANGE;
4372
4373                 ff = buf->lb_buf;
4374                 ol = &ff->ff_layout;
4375                 ol->ol_stripe_count = cpu_to_le32(loa->loa_parent_fid.f_ver >>
4376                                                   PFID_STRIPE_IDX_BITS);
4377                 ol->ol_stripe_size = cpu_to_le32(loa->loa_stripe_size);
4378                 loa->loa_parent_fid.f_ver &= PFID_STRIPE_COUNT_MASK;
4379                 fid_cpu_to_le(&ff->ff_parent, &loa->loa_parent_fid);
4380                 if (lma->lma_compat & LMAC_COMP_INFO) {
4381                         ol->ol_comp_start = cpu_to_le64(loa->loa_comp_start);
4382                         ol->ol_comp_end = cpu_to_le64(loa->loa_comp_end);
4383                         ol->ol_comp_id = cpu_to_le32(loa->loa_comp_id);
4384                 } else {
4385                         ol->ol_comp_start = 0;
4386                         ol->ol_comp_end = 0;
4387                         ol->ol_comp_id = 0;
4388                 }
4389         } else {
4390                 rc = __osd_xattr_get(inode, dentry, name,
4391                                      buf->lb_buf, buf->lb_len);
4392         }
4393
4394         if (cache_xattr) {
4395                 if (rc == -ENOENT || rc == -ENODATA)
4396                         osd_oxc_add(obj, name, NULL, 0);
4397                 else if (rc > 0 && buf->lb_buf != NULL)
4398                         osd_oxc_add(obj, name, buf->lb_buf, rc);
4399         }
4400
4401         return rc;
4402 }
4403
4404 static int osd_declare_xattr_set(const struct lu_env *env,
4405                                  struct dt_object *dt,
4406                                  const struct lu_buf *buf, const char *name,
4407                                  int fl, struct thandle *handle)
4408 {
4409         struct osd_thandle *oh;
4410         int credits = 0;
4411         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4412
4413         LASSERT(handle != NULL);
4414
4415         oh = container_of0(handle, struct osd_thandle, ot_super);
4416         LASSERT(oh->ot_handle == NULL);
4417
4418         if (strcmp(name, XATTR_NAME_LMA) == 0) {
4419                 /*
4420                  * For non-upgrading case, the LMA is set first and
4421                  * usually fit inode. But for upgrade case, the LMA
4422                  * may be in another separated EA block.
4423                  */
4424                 if (dt_object_exists(dt)) {
4425                         if (fl == LU_XATTR_REPLACE)
4426                                 credits = 1;
4427                         else
4428                                 goto upgrade;
4429                 }
4430         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4431                 credits = 1;
4432         } else if (strcmp(name, XATTR_NAME_FID) == 0) {
4433                 /* We may need to delete the old PFID EA. */
4434                 credits = LDISKFS_MAXQUOTAS_DEL_BLOCKS(sb);
4435                 if (fl == LU_XATTR_REPLACE)
4436                         credits += 1;
4437                 else
4438                         goto upgrade;
4439         } else {
4440                 /*
4441                  * If some name entry resides on remote MDT, then will create
4442                  * agent entry under remote parent. On the other hand, if the
4443                  * remote entry will be removed, then related agent entry may
4444                  * need to be removed from the remote parent. So there may be
4445                  * kinds of cases, let's declare enough credits. The credits
4446                  * for create agent entry is enough for remove case.
4447                  */
4448                 if (strcmp(name, XATTR_NAME_LINK) == 0) {
4449                         credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
4450                         if (dt_object_exists(dt))
4451                                 credits += 1; /* For updating LMA */
4452                 }
4453
4454 upgrade:
4455                 credits += osd_dto_credits_noquota[DTO_XATTR_SET];
4456
4457                 if (buf != NULL) {
4458                         ssize_t buflen;
4459
4460                         if (buf->lb_buf == NULL && dt_object_exists(dt)) {
4461                                 /*
4462                                  * learn xattr size from osd_xattr_get if
4463                                  * attribute has not been read yet
4464                                  */
4465                                 buflen = __osd_xattr_get(
4466                                     osd_dt_obj(dt)->oo_inode,
4467                                     &osd_oti_get(env)->oti_obj_dentry,
4468                                     name, NULL, 0);
4469                                 if (buflen < 0)
4470                                         buflen = 0;
4471                         } else {
4472                                 buflen = buf->lb_len;
4473                         }
4474
4475                         if (buflen > sb->s_blocksize) {
4476                                 credits += osd_calc_bkmap_credits(
4477                                     sb, NULL, 0, -1,
4478                                     (buflen + sb->s_blocksize - 1) >>
4479                                     sb->s_blocksize_bits);
4480                         }
4481                 }
4482                 /*
4483                  * xattr set may involve inode quota change, reserve credits for
4484                  * dquot_initialize()
4485                  */
4486                 credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4487         }
4488
4489         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
4490
4491         return 0;
4492 }
4493
4494 static int osd_xattr_set_pfid(const struct lu_env *env, struct osd_object *obj,
4495                               const struct lu_buf *buf, int fl,
4496                               struct thandle *handle)
4497 {
4498         struct osd_thread_info *info = osd_oti_get(env);
4499         struct dentry *dentry = &info->oti_obj_dentry;
4500         struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4501         struct lustre_mdt_attrs *lma = &loa->loa_lma;
4502         struct inode *inode = obj->oo_inode;
4503         struct filter_fid *ff = buf->lb_buf;
4504         struct ost_layout *ol = &ff->ff_layout;
4505         int flags = XATTR_REPLACE;
4506         int rc;
4507
4508         ENTRY;
4509
4510         if (buf->lb_len != sizeof(*ff) && buf->lb_len != sizeof(struct lu_fid))
4511                 RETURN(-EINVAL);
4512
4513         rc = osd_get_lma(info, inode, dentry, loa);
4514         if (rc == -ENODATA) {
4515                 /* Usually for upgarding from old device */
4516                 lustre_loa_init(loa, lu_object_fid(&obj->oo_dt.do_lu),
4517                                 LMAC_FID_ON_OST, 0);
4518                 flags = XATTR_CREATE;
4519         } else if (rc) {
4520                 RETURN(rc);
4521         }
4522
4523         if (!rc && lma->lma_compat & LMAC_STRIPE_INFO) {
4524                 if ((fl & LU_XATTR_CREATE) && !(fl & LU_XATTR_REPLACE))
4525                         RETURN(-EEXIST);
4526
4527                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256) {
4528                         /* Separate PFID EA from LMA */
4529                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4530                         lustre_lma_swab(lma);
4531                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4532                                              sizeof(*lma), XATTR_REPLACE);
4533                         if (!rc) {
4534                                 obj->oo_pfid_in_lma = 0;
4535                                 rc = LU_XATTR_CREATE;
4536                         }
4537
4538                         RETURN(rc);
4539                 }
4540         } else {
4541                 if (LDISKFS_INODE_SIZE(inode->i_sb) > 256)
4542                         RETURN(fl);
4543
4544                 /*
4545                  * Old client does not send stripe information,
4546                  * then store the PFID EA on disk separatedly.
4547                  */
4548                 if (unlikely(buf->lb_len == sizeof(struct lu_fid) ||
4549                              ol->ol_stripe_size == 0))
4550                         RETURN(fl);
4551
4552                 /* Remove old PFID EA entry firstly. */
4553                 ll_vfs_dq_init(inode);
4554                 rc = osd_removexattr(dentry, inode, XATTR_NAME_FID);
4555                 if (rc == -ENODATA) {
4556                         if ((fl & LU_XATTR_REPLACE) && !(fl & LU_XATTR_CREATE))
4557                                 RETURN(rc);
4558                 } else if (rc) {
4559                         RETURN(rc);
4560                 }
4561         }
4562
4563         fid_le_to_cpu(&loa->loa_parent_fid, &ff->ff_parent);
4564         if (likely(ol->ol_stripe_size != 0)) {
4565                 loa->loa_parent_fid.f_ver |= le32_to_cpu(ol->ol_stripe_count) <<
4566                                              PFID_STRIPE_IDX_BITS;
4567                 loa->loa_stripe_size = le32_to_cpu(ol->ol_stripe_size);
4568                 lma->lma_compat |= LMAC_STRIPE_INFO;
4569                 if (ol->ol_comp_id != 0) {
4570                         loa->loa_comp_id = le32_to_cpu(ol->ol_comp_id);
4571                         loa->loa_comp_start = le64_to_cpu(ol->ol_comp_start);
4572                         loa->loa_comp_end = le64_to_cpu(ol->ol_comp_end);
4573                         lma->lma_compat |= LMAC_COMP_INFO;
4574                 }
4575         }
4576
4577         lustre_loa_swab(loa, false);
4578
4579         /* Store the PFID EA inside LMA. */
4580         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, loa, sizeof(*loa),
4581                              flags);
4582         if (!rc)
4583                 obj->oo_pfid_in_lma = 1;
4584
4585         RETURN(rc);
4586 }
4587
4588 /*
4589  * In DNE environment, the object (in spite of regular file or directory)
4590  * and its name entry may reside on different MDTs. Under such case, we will
4591  * create an agent entry on the MDT where the object resides. The agent entry
4592  * references the object locally, that makes the object to be visible to the
4593  * userspace when mounted as 'ldiskfs' directly. Then the userspace tools,
4594  * such as 'tar' can handle the object properly.
4595  *
4596  * We handle the agent entry during set linkEA that is the common interface
4597  * for both regular file and directroy, can handle kinds of cases, such as
4598  * create/link/unlink/rename, and so on.
4599  *
4600  * NOTE: we can NOT do that when ea_{insert,delete} that is only for directory.
4601  *
4602  * XXX: There are two known issues:
4603  * 1. For one object, we will create at most one agent entry even if there
4604  *    may be more than one cross-MDTs hard links on the object. So the local
4605  *    e2fsck may claim that the object's nlink is larger than the name entries
4606  *    that reference such inode. And in further, the e2fsck will fix the nlink
4607  *    attribute to match the local references. Then it will cause the object's
4608  *    nlink attribute to be inconsistent with the global references. it is bad
4609  *    but not fatal. The ref_del() can handle the zero-referenced case. On the
4610  *    other hand, the global namespace LFSCK can repair the object's attribute
4611  *    according to the linkEA.
4612  * 2. There may be too many hard links on the object as to its linkEA overflow,
4613  *    then the linkEA entry for cross-MDTs reference may be discarded. If such
4614  *    case happened, then at this point, we do not know whether there are some
4615  *    cross-MDTs reference. But there are local references, it guarantees that
4616  *    object is visible to userspace when mounted as 'ldiskfs'. That is enough.
4617  */
4618 static int osd_xattr_handle_linkea(const struct lu_env *env,
4619                                    struct osd_device *osd,
4620                                    struct osd_object *obj,
4621                                    const struct lu_buf *buf,
4622                                    struct thandle *handle)
4623 {
4624         const struct lu_fid *fid = lu_object_fid(&obj->oo_dt.do_lu);
4625         struct lu_fid *tfid = &osd_oti_get(env)->oti_fid3;
4626         struct linkea_data ldata = { .ld_buf = (struct lu_buf *)buf };
4627         struct lu_name tmpname;
4628         struct osd_thandle *oh;
4629         int rc;
4630         bool remote = false;
4631
4632         ENTRY;
4633
4634         oh = container_of0(handle, struct osd_thandle, ot_super);
4635         LASSERT(oh->ot_handle != NULL);
4636
4637         rc = linkea_init_with_rec(&ldata);
4638         if (!rc) {
4639                 linkea_first_entry(&ldata);
4640                 while (ldata.ld_lee != NULL && !remote) {
4641                         linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen,
4642                                             &tmpname, tfid);
4643                         if (osd_remote_fid(env, osd, tfid) > 0)
4644                                 remote = true;
4645                         else
4646                                 linkea_next_entry(&ldata);
4647                 }
4648         } else if (rc == -ENODATA) {
4649                 rc = 0;
4650         } else {
4651                 RETURN(rc);
4652         }
4653
4654         if (lu_object_has_agent_entry(&obj->oo_dt.do_lu) && !remote) {
4655                 rc = osd_delete_from_remote_parent(env, osd, obj, oh, false);
4656                 if (rc)
4657                         CERROR("%s: failed to remove agent entry for "DFID
4658                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4659         } else if (!lu_object_has_agent_entry(&obj->oo_dt.do_lu) && remote) {
4660                 rc = osd_add_to_remote_parent(env, osd, obj, oh);
4661                 if (rc)
4662                         CERROR("%s: failed to create agent entry for "DFID
4663                                ": rc = %d\n", osd_name(osd), PFID(fid), rc);
4664         }
4665
4666         RETURN(rc);
4667 }
4668
4669 /*
4670  * Concurrency: @dt is write locked.
4671  */
4672 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
4673                          const struct lu_buf *buf, const char *name, int fl,
4674                          struct thandle *handle)
4675 {
4676         struct osd_object *obj = osd_dt_obj(dt);
4677         struct osd_device *osd = osd_obj2dev(obj);
4678         struct inode *inode = obj->oo_inode;
4679         struct osd_thread_info *info = osd_oti_get(env);
4680         int fs_flags = 0;
4681         int len;
4682         int rc;
4683
4684         ENTRY;
4685
4686         LASSERT(handle);
4687         LASSERT(buf);
4688
4689         /* version set is not real XATTR */
4690         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
4691                 dt_obj_version_t *version = buf->lb_buf;
4692
4693                 /*
4694                  * for version we are just using xattr API but change inode
4695                  * field instead
4696                  */
4697                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
4698
4699                 CDEBUG(D_INODE, "Set version %#llx (old %#llx) for inode %lu\n",
4700                        *version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
4701
4702                 LDISKFS_I(inode)->i_fs_version = *version;
4703                 /*
4704                  * Version is set after all inode operations are finished,
4705                  * so we should mark it dirty here
4706                  */
4707                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
4708
4709                 RETURN(0);
4710         }
4711
4712         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zu\n",
4713                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
4714
4715         len = buf->lb_len;
4716         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4717
4718         /*
4719          * For the OST device with 256 bytes inode size by default,
4720          * the PFID EA will be stored together with LMA EA to avoid
4721          * performance trouble. Otherwise the PFID EA can be stored
4722          * independently. LU-8998
4723          */
4724         if (strcmp(name, XATTR_NAME_FID) == 0 && osd->od_is_ost &&
4725             (LDISKFS_INODE_SIZE(inode->i_sb) <= 256 || obj->oo_pfid_in_lma)) {
4726                 LASSERT(buf->lb_buf);
4727
4728                 fl = osd_xattr_set_pfid(env, obj, buf, fl, handle);
4729                 if (fl <= 0)
4730                         RETURN(fl);
4731         } else if (strcmp(name, XATTR_NAME_LMV) == 0) {
4732                 struct lustre_ost_attrs *loa = &info->oti_ost_attrs;
4733                 struct lustre_mdt_attrs *lma = &loa->loa_lma;
4734
4735                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, loa);
4736                 if (rc)
4737                         RETURN(rc);
4738
4739                 lma->lma_incompat |= LMAI_STRIPED;
4740                 lustre_lma_swab(lma);
4741                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4742                                      sizeof(*lma), XATTR_REPLACE);
4743                 if (rc != 0)
4744                         RETURN(rc);
4745         } else if (strcmp(name, XATTR_NAME_LINK) == 0) {
4746                 LASSERT(!osd->od_is_ost);
4747
4748                 rc = osd_xattr_handle_linkea(env, osd, obj, buf, handle);
4749                 if (rc)
4750                         RETURN(rc);
4751         }
4752
4753         if (fl & LU_XATTR_REPLACE)
4754                 fs_flags |= XATTR_REPLACE;
4755
4756         if (fl & LU_XATTR_CREATE)
4757                 fs_flags |= XATTR_CREATE;
4758
4759         rc = __osd_xattr_set(info, inode, name, buf->lb_buf, len, fs_flags);
4760         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4761
4762         if (rc == 0 &&
4763             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4764              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4765                 osd_oxc_add(obj, name, buf->lb_buf, buf->lb_len);
4766
4767         return rc;
4768 }
4769
4770 /*
4771  * Concurrency: @dt is read locked.
4772  */
4773 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
4774                           const struct lu_buf *buf)
4775 {
4776         struct osd_object *obj = osd_dt_obj(dt);
4777         struct inode *inode = obj->oo_inode;
4778         struct osd_thread_info *info = osd_oti_get(env);
4779         struct dentry *dentry = &info->oti_obj_dentry;
4780
4781         if (!dt_object_exists(dt))
4782                 return -ENOENT;
4783
4784         LASSERT(!dt_object_remote(dt));
4785         LASSERT(inode->i_op != NULL);
4786         LASSERT(inode->i_op->listxattr != NULL);
4787
4788         dentry->d_inode = inode;
4789         dentry->d_sb = inode->i_sb;
4790         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
4791 }
4792
4793 static int osd_declare_xattr_del(const struct lu_env *env,
4794                                  struct dt_object *dt, const char *name,
4795                                  struct thandle *handle)
4796 {
4797         struct osd_thandle *oh;
4798         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
4799
4800         LASSERT(!dt_object_remote(dt));
4801         LASSERT(handle != NULL);
4802
4803         oh = container_of0(handle, struct osd_thandle, ot_super);
4804         LASSERT(oh->ot_handle == NULL);
4805
4806         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
4807                              osd_dto_credits_noquota[DTO_XATTR_SET]);
4808         /*
4809          * xattr del may involve inode quota change, reserve credits for
4810          * dquot_initialize()
4811          */
4812         oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
4813
4814         return 0;
4815 }
4816
4817 /*
4818  * Concurrency: @dt is write locked.
4819  */
4820 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
4821                          const char *name, struct thandle *handle)
4822 {
4823         struct osd_object *obj = osd_dt_obj(dt);
4824         struct inode *inode = obj->oo_inode;
4825         struct osd_thread_info *info = osd_oti_get(env);
4826         struct dentry *dentry = &info->oti_obj_dentry;
4827         int rc;
4828
4829         if (!dt_object_exists(dt))
4830                 return -ENOENT;
4831
4832         LASSERT(!dt_object_remote(dt));
4833         LASSERT(inode->i_op != NULL);
4834         LASSERT(handle != NULL);
4835 #ifdef HAVE_IOP_XATTR
4836         LASSERT(inode->i_op->removexattr != NULL);
4837 #endif
4838
4839         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
4840
4841         if (strcmp(name, XATTR_NAME_FID) == 0 && obj->oo_pfid_in_lma) {
4842                 struct lustre_mdt_attrs *lma = &info->oti_ost_attrs.loa_lma;
4843
4844                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry,
4845                                  &info->oti_ost_attrs);
4846                 if (!rc) {
4847                         LASSERT(lma->lma_compat & LMAC_STRIPE_INFO);
4848
4849                         lma->lma_compat &= ~(LMAC_STRIPE_INFO | LMAC_COMP_INFO);
4850                         lustre_lma_swab(lma);
4851                         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
4852                                              sizeof(*lma), XATTR_REPLACE);
4853                         if (!rc)
4854                                 obj->oo_pfid_in_lma = 0;
4855                 }
4856         } else {
4857                 ll_vfs_dq_init(inode);
4858                 dentry->d_inode = inode;
4859                 dentry->d_sb = inode->i_sb;
4860                 rc = osd_removexattr(dentry, inode, name);
4861         }
4862
4863         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
4864
4865         if (rc == 0 &&
4866             (strcmp(name, XATTR_NAME_LOV) == 0 ||
4867              strcmp(name, XATTR_NAME_DEFAULT_LMV) == 0))
4868                 osd_oxc_del(obj, name);
4869
4870         return rc;
4871 }
4872
4873 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt,
4874                            __u64 start, __u64 end)
4875 {
4876         struct osd_object *obj = osd_dt_obj(dt);
4877         struct inode *inode = obj->oo_inode;
4878         struct osd_thread_info *info = osd_oti_get(env);
4879         struct dentry *dentry = &info->oti_obj_dentry;
4880         struct file *file = &info->oti_file;
4881         int rc;
4882
4883         ENTRY;
4884
4885         dentry->d_inode = inode;
4886         dentry->d_sb = inode->i_sb;
4887         file->f_path.dentry = dentry;
4888         file->f_mapping = inode->i_mapping;
4889         file->f_op = inode->i_fop;
4890         set_file_inode(file, inode);
4891
4892         rc = ll_vfs_fsync_range(file, start, end, 0);
4893
4894         RETURN(rc);
4895 }
4896
4897 static int osd_invalidate(const struct lu_env *env, struct dt_object *dt)
4898 {
4899         return 0;
4900 }
4901
4902 /*
4903  * Index operations.
4904  */
4905
4906 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
4907                                const struct dt_index_features *feat)
4908 {
4909         struct iam_descr *descr;
4910
4911         if (osd_object_is_root(o))
4912                 return feat == &dt_directory_features;
4913
4914         LASSERT(o->oo_dir != NULL);
4915
4916         descr = o->oo_dir->od_container.ic_descr;
4917         if (feat == &dt_directory_features) {
4918                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
4919                         return 1;
4920                 else
4921                         return 0;
4922         } else {
4923                 return feat->dif_keysize_min <= descr->id_key_size &&
4924                        descr->id_key_size <= feat->dif_keysize_max &&
4925                        feat->dif_recsize_min <= descr->id_rec_size &&
4926                        descr->id_rec_size <= feat->dif_recsize_max &&
4927                        !(feat->dif_flags & (DT_IND_VARKEY |
4928                                             DT_IND_VARREC | DT_IND_NONUNQ)) &&
4929                        ergo(feat->dif_flags & DT_IND_UPDATE,
4930                             1 /* XXX check that object (and fs) is writable */);
4931         }
4932 }
4933
4934 static int osd_iam_container_init(const struct lu_env *env,
4935                                   struct osd_object *obj,
4936                                   struct osd_directory *dir)
4937 {
4938         struct iam_container *bag = &dir->od_container;
4939         int result;
4940
4941         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
4942         if (result != 0)
4943                 return result;
4944
4945         result = iam_container_setup(bag);
4946         if (result == 0)
4947                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
4948         else
4949                 iam_container_fini(bag);
4950
4951         return result;
4952 }
4953
4954
4955 /*
4956  * Concurrency: no external locking is necessary.
4957  */
4958 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
4959                          const struct dt_index_features *feat)
4960 {
4961         int result;
4962         int skip_iam = 0;
4963         struct osd_object *obj = osd_dt_obj(dt);
4964
4965         LINVRNT(osd_invariant(obj));
4966
4967         if (osd_object_is_root(obj)) {
4968                 dt->do_index_ops = &osd_index_ea_ops;
4969                 result = 0;
4970         } else if (feat == &dt_directory_features) {
4971                 dt->do_index_ops = &osd_index_ea_ops;
4972                 if (obj->oo_inode == NULL || S_ISDIR(obj->oo_inode->i_mode))
4973                         result = 0;
4974                 else
4975                         result = -ENOTDIR;
4976                 skip_iam = 1;
4977         } else if (unlikely(feat == &dt_otable_features)) {
4978                 dt->do_index_ops = &osd_otable_ops;
4979                 return 0;
4980         } else if (unlikely(feat == &dt_acct_features)) {
4981                 dt->do_index_ops = &osd_acct_index_ops;
4982                 result = 0;
4983                 skip_iam = 1;
4984         } else if (!osd_has_index(obj)) {
4985                 struct osd_directory *dir;
4986                 struct osd_device *osd = osd_obj2dev(obj);
4987                 const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
4988
4989                 OBD_ALLOC_PTR(dir);
4990                 if (dir) {
4991
4992                         spin_lock(&obj->oo_guard);
4993                         if (obj->oo_dir == NULL)
4994                                 obj->oo_dir = dir;
4995                         else
4996                                 /*
4997                                  * Concurrent thread allocated container data.
4998                                  */
4999                                 OBD_FREE_PTR(dir);
5000                         spin_unlock(&obj->oo_guard);
5001                         /*
5002                          * Now, that we have container data, serialize its
5003                          * initialization.
5004                          */
5005                         down_write(&obj->oo_ext_idx_sem);
5006                         /*
5007                          * recheck under lock.
5008                          */
5009
5010                         if (osd_has_index(obj)) {
5011                                 result = 0;
5012                                 goto unlock;
5013                         }
5014
5015                         result = osd_iam_container_init(env, obj, obj->oo_dir);
5016                         if (result || feat == &dt_lfsck_namespace_features ||
5017                             feat == &dt_lfsck_layout_orphan_features ||
5018                             feat == &dt_lfsck_layout_dangling_features)
5019                                 goto unlock;
5020
5021                         result = osd_index_register(osd, fid,
5022                                                     feat->dif_keysize_max,
5023                                                     feat->dif_recsize_max);
5024                         if (result < 0)
5025                                 CWARN("%s: failed to register index "
5026                                       DFID": rc = %d\n",
5027                                       osd_name(osd), PFID(fid), result);
5028                         else if (result > 0)
5029                                 result = 0;
5030                         else
5031                                 CDEBUG(D_LFSCK, "%s: index object "DFID
5032                                        " (%d/%d) registered\n",
5033                                        osd_name(osd), PFID(fid),
5034                                        (int)feat->dif_keysize_max,
5035                                        (int)feat->dif_recsize_max);
5036
5037 unlock:
5038                         up_write(&obj->oo_ext_idx_sem);
5039                 } else {
5040                         result = -ENOMEM;
5041                 }
5042         } else {
5043                 result = 0;
5044         }
5045
5046         if (result == 0 && skip_iam == 0) {
5047                 if (!osd_iam_index_probe(env, obj, feat))
5048                         result = -ENOTDIR;
5049         }
5050         LINVRNT(osd_invariant(obj));
5051
5052         return result;
5053 }
5054
5055 static int osd_otable_it_attr_get(const struct lu_env *env,
5056                                  struct dt_object *dt,
5057                                  struct lu_attr *attr)
5058 {
5059         attr->la_valid = 0;
5060         return 0;
5061 }
5062
5063 static const struct dt_object_operations osd_obj_ops = {
5064         .do_read_lock           = osd_read_lock,
5065         .do_write_lock          = osd_write_lock,
5066         .do_read_unlock         = osd_read_unlock,
5067         .do_write_unlock        = osd_write_unlock,
5068         .do_write_locked        = osd_write_locked,
5069         .do_attr_get            = osd_attr_get,
5070         .do_declare_attr_set    = osd_declare_attr_set,
5071         .do_attr_set            = osd_attr_set,
5072         .do_ah_init             = osd_ah_init,
5073         .do_declare_create      = osd_declare_create,
5074         .do_create              = osd_create,
5075         .do_declare_destroy     = osd_declare_destroy,
5076         .do_destroy             = osd_destroy,
5077         .do_index_try           = osd_index_try,
5078         .do_declare_ref_add     = osd_declare_ref_add,
5079         .do_ref_add             = osd_ref_add,
5080         .do_declare_ref_del     = osd_declare_ref_del,
5081         .do_ref_del             = osd_ref_del,
5082         .do_xattr_get           = osd_xattr_get,
5083         .do_declare_xattr_set   = osd_declare_xattr_set,
5084         .do_xattr_set           = osd_xattr_set,
5085         .do_declare_xattr_del   = osd_declare_xattr_del,
5086         .do_xattr_del           = osd_xattr_del,
5087         .do_xattr_list          = osd_xattr_list,
5088         .do_object_sync         = osd_object_sync,
5089         .do_invalidate          = osd_invalidate,
5090 };
5091
5092 static const struct dt_object_operations osd_obj_otable_it_ops = {
5093         .do_attr_get    = osd_otable_it_attr_get,
5094         .do_index_try   = osd_index_try,
5095 };
5096
5097 static int osd_index_declare_iam_delete(const struct lu_env *env,
5098                                         struct dt_object *dt,
5099                                         const struct dt_key *key,
5100                                         struct thandle *handle)
5101 {
5102         struct osd_thandle *oh;
5103
5104         oh = container_of0(handle, struct osd_thandle, ot_super);
5105         LASSERT(oh->ot_handle == NULL);
5106
5107         /* Recycle  may cause additional three blocks to be changed. */
5108         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
5109                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
5110
5111         return 0;
5112 }
5113
5114 /**
5115  *      delete a (key, value) pair from index \a dt specified by \a key
5116  *
5117  *      \param  dt      osd index object
5118  *      \param  key     key for index
5119  *      \param  rec     record reference
5120  *      \param  handle  transaction handler
5121  *
5122  *      \retval  0  success
5123  *      \retval -ve   failure
5124  */
5125 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
5126                                 const struct dt_key *key,
5127                                 struct thandle *handle)
5128 {
5129         struct osd_thread_info *oti = osd_oti_get(env);
5130         struct osd_object *obj = osd_dt_obj(dt);
5131         struct osd_thandle *oh;
5132         struct iam_path_descr *ipd;
5133         struct iam_container *bag = &obj->oo_dir->od_container;
5134         int rc;
5135
5136         ENTRY;
5137
5138         if (!dt_object_exists(dt))
5139                 RETURN(-ENOENT);
5140
5141         LINVRNT(osd_invariant(obj));
5142         LASSERT(!dt_object_remote(dt));
5143         LASSERT(bag->ic_object == obj->oo_inode);
5144         LASSERT(handle != NULL);
5145
5146         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5147
5148         ipd = osd_idx_ipd_get(env, bag);
5149         if (unlikely(ipd == NULL))
5150                 RETURN(-ENOMEM);
5151
5152         oh = container_of0(handle, struct osd_thandle, ot_super);
5153         LASSERT(oh->ot_handle != NULL);
5154         LASSERT(oh->ot_handle->h_transaction != NULL);
5155
5156         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5157                 /* swab quota uid/gid provided by caller */
5158                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5159                 key = (const struct dt_key *)&oti->oti_quota_id;
5160         }
5161
5162         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
5163         osd_ipd_put(env, bag, ipd);
5164         LINVRNT(osd_invariant(obj));
5165         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5166         RETURN(rc);
5167 }
5168
5169 static int osd_index_declare_ea_delete(const struct lu_env *env,
5170                                        struct dt_object *dt,
5171                                        const struct dt_key *key,
5172                                        struct thandle *handle)
5173 {
5174         struct osd_thandle *oh;
5175         struct inode *inode;
5176         int rc, credits;
5177
5178         ENTRY;
5179
5180         LASSERT(!dt_object_remote(dt));
5181         LASSERT(handle != NULL);
5182
5183         oh = container_of0(handle, struct osd_thandle, ot_super);
5184         LASSERT(oh->ot_handle == NULL);
5185
5186         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE];
5187         osd_trans_declare_op(env, oh, OSD_OT_DELETE, credits);
5188
5189         inode = osd_dt_obj(dt)->oo_inode;
5190         if (inode == NULL)
5191                 RETURN(-ENOENT);
5192
5193         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
5194                                    i_projid_read(inode), 0, oh, osd_dt_obj(dt),
5195                                    NULL, OSD_QID_BLK);
5196         RETURN(rc);
5197 }
5198
5199 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
5200                                           struct dt_rec *fid)
5201 {
5202         struct osd_fid_pack *rec;
5203         int rc = -ENODATA;
5204
5205         if (de->file_type & LDISKFS_DIRENT_LUFID) {
5206                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
5207                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
5208                 if (rc == 0 && unlikely(!fid_is_sane((struct lu_fid *)fid)))
5209                         rc = -EINVAL;
5210         }
5211         return rc;
5212 }
5213
5214 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
5215                           const struct lu_fid *fid)
5216 {
5217         struct seq_server_site *ss = osd_seq_site(osd);
5218
5219         ENTRY;
5220
5221         /* FID seqs not in FLDB, must be local seq */
5222         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
5223                 RETURN(0);
5224
5225         /*
5226          * If FLD is not being initialized yet, it only happens during the
5227          * initialization, likely during mgs initialization, and we assume
5228          * this is local FID.
5229          */
5230         if (ss == NULL || ss->ss_server_fld == NULL)
5231                 RETURN(0);
5232
5233         /* Only check the local FLDB here */
5234         if (osd_seq_exists(env, osd, fid_seq(fid)))
5235                 RETURN(0);
5236
5237         RETURN(1);
5238 }
5239
5240 static void osd_take_care_of_agent(const struct lu_env *env,
5241                                    struct osd_device *osd,
5242                                    struct osd_thandle *oh,
5243                                    struct ldiskfs_dir_entry_2 *de)
5244 {
5245         struct lu_fid *fid = &osd_oti_get(env)->oti_fid;
5246         struct osd_idmap_cache *idc;
5247         int rc, schedule = 0;
5248
5249         LASSERT(de != NULL);
5250
5251         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
5252         if (likely(rc == 0)) {
5253                 idc = osd_idc_find_or_init(env, osd, fid);
5254                 if (IS_ERR(idc) || idc->oic_remote)
5255                         schedule = 1;
5256         } else if (rc == -ENODATA) {
5257                 /*
5258                  * can't get FID, postpone to the end of the
5259                  * transaction when iget() is safe
5260                  */
5261                 schedule = 1;
5262         } else {
5263                 CERROR("%s: can't get FID: rc = %d\n", osd_name(osd), rc);
5264         }
5265         if (schedule)
5266                 osd_schedule_agent_inode_removal(env, oh,
5267                                                  le32_to_cpu(de->inode));
5268 }
5269
5270 /**
5271  * Index delete function for interoperability mode (b11826).
5272  * It will remove the directory entry added by osd_index_ea_insert().
5273  * This entry is needed to maintain name->fid mapping.
5274  *
5275  * \param key,  key i.e. file entry to be deleted
5276  *
5277  * \retval   0, on success
5278  * \retval -ve, on error
5279  */
5280 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
5281                                const struct dt_key *key, struct thandle *handle)
5282 {
5283         struct osd_object *obj = osd_dt_obj(dt);
5284         struct inode *dir = obj->oo_inode;
5285         struct dentry *dentry;
5286         struct osd_thandle *oh;
5287         struct ldiskfs_dir_entry_2 *de = NULL;
5288         struct buffer_head *bh;
5289         struct htree_lock *hlock = NULL;
5290         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
5291         int rc;
5292
5293         ENTRY;
5294
5295         if (!dt_object_exists(dt))
5296                 RETURN(-ENOENT);
5297
5298         LINVRNT(osd_invariant(obj));
5299         LASSERT(!dt_object_remote(dt));
5300         LASSERT(handle != NULL);
5301
5302         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
5303
5304         oh = container_of(handle, struct osd_thandle, ot_super);
5305         LASSERT(oh->ot_handle != NULL);
5306         LASSERT(oh->ot_handle->h_transaction != NULL);
5307
5308         ll_vfs_dq_init(dir);
5309         dentry = osd_child_dentry_get(env, obj,
5310                                       (char *)key, strlen((char *)key));
5311
5312         if (obj->oo_hl_head != NULL) {
5313                 hlock = osd_oti_get(env)->oti_hlock;
5314                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5315                                    dir, LDISKFS_HLOCK_DEL);
5316         } else {
5317                 down_write(&obj->oo_ext_idx_sem);
5318         }
5319
5320         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5321         if (!IS_ERR(bh)) {
5322                 /*
5323                  * If this is not the ".." entry, it might be a remote DNE
5324                  * entry and  we need to check if the FID is for a remote
5325                  * MDT.  If the FID is  not in the directory entry (e.g.
5326                  * upgraded 1.8 filesystem without dirdata enabled) then
5327                  * we need to get the FID from the LMA. For a remote directory
5328                  * there HAS to be an LMA, it cannot be an IGIF inode in this
5329                  * case.
5330                  *
5331                  * Delete the entry before the agent inode in order to
5332                  * simplify error handling.  At worst an error after deleting
5333                  * the entry first might leak the agent inode afterward. The
5334                  * reverse would need filesystem abort in case of error deleting
5335                  * the entry after the agent had been removed, or leave a
5336                  * dangling entry pointing at a random inode.
5337                  */
5338                 if (strcmp((char *)key, dotdot) != 0)
5339                         osd_take_care_of_agent(env, osd, oh, de);
5340                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
5341                 brelse(bh);
5342         } else {
5343                 rc = PTR_ERR(bh);
5344         }
5345         if (hlock != NULL)
5346                 ldiskfs_htree_unlock(hlock);
5347         else
5348                 up_write(&obj->oo_ext_idx_sem);
5349
5350         GOTO(out, rc);
5351 out:
5352         LASSERT(osd_invariant(obj));
5353         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
5354         RETURN(rc);
5355 }
5356
5357 /**
5358  *      Lookup index for \a key and copy record to \a rec.
5359  *
5360  *      \param  dt      osd index object
5361  *      \param  key     key for index
5362  *      \param  rec     record reference
5363  *
5364  *      \retval  +ve  success : exact mach
5365  *      \retval  0    return record with key not greater than \a key
5366  *      \retval -ve   failure
5367  */
5368 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
5369                                 struct dt_rec *rec, const struct dt_key *key)
5370 {
5371         struct osd_object *obj = osd_dt_obj(dt);
5372         struct iam_path_descr *ipd;
5373         struct iam_container *bag = &obj->oo_dir->od_container;
5374         struct osd_thread_info *oti = osd_oti_get(env);
5375         struct iam_iterator *it = &oti->oti_idx_it;
5376         struct iam_rec *iam_rec;
5377         int rc;
5378
5379         ENTRY;
5380
5381         if (!dt_object_exists(dt))
5382                 RETURN(-ENOENT);
5383
5384         LASSERT(osd_invariant(obj));
5385         LASSERT(!dt_object_remote(dt));
5386         LASSERT(bag->ic_object == obj->oo_inode);
5387
5388         ipd = osd_idx_ipd_get(env, bag);
5389         if (IS_ERR(ipd))
5390                 RETURN(-ENOMEM);
5391
5392         /* got ipd now we can start iterator. */
5393         iam_it_init(it, bag, 0, ipd);
5394
5395         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5396                 /* swab quota uid/gid provided by caller */
5397                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5398                 key = (const struct dt_key *)&oti->oti_quota_id;
5399         }
5400
5401         rc = iam_it_get(it, (struct iam_key *)key);
5402         if (rc >= 0) {
5403                 if (S_ISDIR(obj->oo_inode->i_mode))
5404                         iam_rec = (struct iam_rec *)oti->oti_ldp;
5405                 else
5406                         iam_rec = (struct iam_rec *)rec;
5407
5408                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
5409
5410                 if (S_ISDIR(obj->oo_inode->i_mode))
5411                         osd_fid_unpack((struct lu_fid *)rec,
5412                                        (struct osd_fid_pack *)iam_rec);
5413                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
5414                         osd_quota_unpack(obj, rec);
5415         }
5416
5417         iam_it_put(it);
5418         iam_it_fini(it);
5419         osd_ipd_put(env, bag, ipd);
5420
5421         LINVRNT(osd_invariant(obj));
5422
5423         RETURN(rc);
5424 }
5425
5426 static int osd_index_declare_iam_insert(const struct lu_env *env,
5427                                         struct dt_object *dt,
5428                                         const struct dt_rec *rec,
5429                                         const struct dt_key *key,
5430                                         struct thandle *handle)
5431 {
5432         struct osd_thandle *oh;
5433
5434         LASSERT(handle != NULL);
5435
5436         oh = container_of0(handle, struct osd_thandle, ot_super);
5437         LASSERT(oh->ot_handle == NULL);
5438
5439         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
5440                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
5441
5442         return 0;
5443 }
5444
5445 /**
5446  *      Inserts (key, value) pair in \a dt index object.
5447  *
5448  *      \param  dt      osd index object
5449  *      \param  key     key for index
5450  *      \param  rec     record reference
5451  *      \param  th      transaction handler
5452  *
5453  *      \retval  0  success
5454  *      \retval -ve failure
5455  */
5456 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
5457                                 const struct dt_rec *rec,
5458                                 const struct dt_key *key, struct thandle *th)
5459 {
5460         struct osd_object *obj = osd_dt_obj(dt);
5461         struct iam_path_descr *ipd;
5462         struct osd_thandle *oh;
5463         struct iam_container *bag;
5464         struct osd_thread_info *oti = osd_oti_get(env);
5465         struct iam_rec *iam_rec;
5466         int rc;
5467
5468         ENTRY;
5469
5470         if (!dt_object_exists(dt))
5471                 RETURN(-ENOENT);
5472
5473         LINVRNT(osd_invariant(obj));
5474         LASSERT(!dt_object_remote(dt));
5475
5476         bag = &obj->oo_dir->od_container;
5477         LASSERT(bag->ic_object == obj->oo_inode);
5478         LASSERT(th != NULL);
5479
5480         osd_trans_exec_op(env, th, OSD_OT_INSERT);
5481
5482         ipd = osd_idx_ipd_get(env, bag);
5483         if (unlikely(ipd == NULL))
5484                 RETURN(-ENOMEM);
5485
5486         oh = container_of0(th, struct osd_thandle, ot_super);
5487         LASSERT(oh->ot_handle != NULL);
5488         LASSERT(oh->ot_handle->h_transaction != NULL);
5489         if (S_ISDIR(obj->oo_inode->i_mode)) {
5490                 iam_rec = (struct iam_rec *)oti->oti_ldp;
5491                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec,
5492                              &oti->oti_fid);
5493         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
5494                 /* pack quota uid/gid */
5495                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
5496                 key = (const struct dt_key *)&oti->oti_quota_id;
5497                 /* pack quota record */
5498                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
5499                 iam_rec = (struct iam_rec *)rec;
5500         } else {
5501                 iam_rec = (struct iam_rec *)rec;
5502         }
5503
5504         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
5505                         iam_rec, ipd);
5506         osd_ipd_put(env, bag, ipd);
5507         LINVRNT(osd_invariant(obj));
5508         osd_trans_exec_check(env, th, OSD_OT_INSERT);
5509         RETURN(rc);
5510 }
5511
5512 /**
5513  * Calls ldiskfs_add_entry() to add directory entry
5514  * into the directory. This is required for
5515  * interoperability mode (b11826)
5516  *
5517  * \retval   0, on success
5518  * \retval -ve, on error
5519  */
5520 static int __osd_ea_add_rec(struct osd_thread_info *info,
5521                             struct osd_object *pobj, struct inode  *cinode,
5522                             const char *name, const struct lu_fid *fid,
5523                             struct htree_lock *hlock, struct thandle *th)
5524 {
5525         struct ldiskfs_dentry_param *ldp;
5526         struct dentry *child;
5527         struct osd_thandle *oth;
5528         int rc;
5529
5530         oth = container_of(th, struct osd_thandle, ot_super);
5531         LASSERT(oth->ot_handle != NULL);
5532         LASSERT(oth->ot_handle->h_transaction != NULL);
5533         LASSERT(pobj->oo_inode);
5534
5535         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
5536         if (unlikely(pobj->oo_inode ==
5537                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
5538                 ldp->edp_magic = 0;
5539         else
5540                 osd_get_ldiskfs_dirent_param(ldp, fid);
5541         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
5542         child->d_fsdata = (void *)ldp;
5543         ll_vfs_dq_init(pobj->oo_inode);
5544         rc = osd_ldiskfs_add_entry(info, osd_obj2dev(pobj), oth->ot_handle,
5545                                    child, cinode, hlock);
5546         if (rc == 0 && OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_TYPE)) {
5547                 struct ldiskfs_dir_entry_2      *de;
5548                 struct buffer_head              *bh;
5549                 int                              rc1;
5550
5551                 bh = osd_ldiskfs_find_entry(pobj->oo_inode, &child->d_name, &de,
5552                                             NULL, hlock);
5553                 if (!IS_ERR(bh)) {
5554                         rc1 = ldiskfs_journal_get_write_access(oth->ot_handle,
5555                                                                bh);
5556                         if (rc1 == 0) {
5557                                 if (S_ISDIR(cinode->i_mode))
5558                                         de->file_type = LDISKFS_DIRENT_LUFID |
5559                                                         LDISKFS_FT_REG_FILE;
5560                                 else
5561                                         de->file_type = LDISKFS_DIRENT_LUFID |
5562                                                         LDISKFS_FT_DIR;
5563                                 ldiskfs_handle_dirty_metadata(oth->ot_handle,
5564                                                               NULL, bh);
5565                         }
5566                         brelse(bh);
5567                 }
5568         }
5569
5570         RETURN(rc);
5571 }
5572
5573 /**
5574  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
5575  * into the directory.Also sets flags into osd object to
5576  * indicate dot and dotdot are created. This is required for
5577  * interoperability mode (b11826)
5578  *
5579  * \param dir   directory for dot and dotdot fixup.
5580  * \param obj   child object for linking
5581  *
5582  * \retval   0, on success
5583  * \retval -ve, on error
5584  */
5585 static int osd_add_dot_dotdot(struct osd_thread_info *info,
5586                               struct osd_object *dir,
5587                               struct inode *parent_dir, const char *name,
5588                               const struct lu_fid *dot_fid,
5589                               const struct lu_fid *dot_dot_fid,
5590                               struct thandle *th)
5591 {
5592         struct inode *inode = dir->oo_inode;
5593         struct osd_thandle *oth;
5594         int result = 0;
5595
5596         oth = container_of(th, struct osd_thandle, ot_super);
5597         LASSERT(oth->ot_handle->h_transaction != NULL);
5598         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
5599
5600         if (strcmp(name, dot) == 0) {
5601                 if (dir->oo_compat_dot_created) {
5602                         result = -EEXIST;
5603                 } else {
5604                         LASSERT(inode->i_ino == parent_dir->i_ino);
5605                         dir->oo_compat_dot_created = 1;
5606                         result = 0;
5607                 }
5608         } else if (strcmp(name, dotdot) == 0) {
5609                 if (!dir->oo_compat_dot_created)
5610                         return -EINVAL;
5611                 /* in case of rename, dotdot is already created */
5612                 if (dir->oo_compat_dotdot_created) {
5613                         return __osd_ea_add_rec(info, dir, parent_dir, name,
5614                                                 dot_dot_fid, NULL, th);
5615                 }
5616
5617                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
5618                         struct lu_fid tfid = *dot_dot_fid;
5619
5620                         tfid.f_oid--;
5621                         result = osd_add_dot_dotdot_internal(info,
5622                                         dir->oo_inode, parent_dir, dot_fid,
5623                                         &tfid, oth);
5624                 } else {
5625                         result = osd_add_dot_dotdot_internal(info,
5626                                         dir->oo_inode, parent_dir, dot_fid,
5627                                         dot_dot_fid, oth);
5628                 }
5629
5630                 if (result == 0)
5631                         dir->oo_compat_dotdot_created = 1;
5632         }
5633
5634         return result;
5635 }
5636
5637
5638 /**
5639  * It will call the appropriate osd_add* function and return the
5640  * value, return by respective functions.
5641  */
5642 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
5643                           struct inode *cinode, const char *name,
5644                           const struct lu_fid *fid, struct thandle *th)
5645 {
5646         struct osd_thread_info *info = osd_oti_get(env);
5647         struct htree_lock *hlock;
5648         int rc;
5649
5650         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
5651
5652         if (name[0] == '.' && (name[1] == '\0' ||
5653                                (name[1] == '.' && name[2] == '\0'))) {
5654                 if (hlock != NULL) {
5655                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5656                                            pobj->oo_inode, 0);
5657                 } else {
5658                         down_write(&pobj->oo_ext_idx_sem);
5659                 }
5660
5661                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
5662                                         lu_object_fid(&pobj->oo_dt.do_lu),
5663                                         fid, th);
5664         } else {
5665                 if (hlock != NULL) {
5666                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
5667                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
5668                 } else {
5669                         down_write(&pobj->oo_ext_idx_sem);
5670                 }
5671
5672                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
5673                         struct lu_fid *tfid = &info->oti_fid;
5674
5675                         *tfid = *fid;
5676                         tfid->f_ver = ~0;
5677                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
5678                                               tfid, hlock, th);
5679                 } else {
5680                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
5681                                               hlock, th);
5682                 }
5683         }
5684         if (hlock != NULL)
5685                 ldiskfs_htree_unlock(hlock);
5686         else
5687                 up_write(&pobj->oo_ext_idx_sem);
5688
5689         return rc;
5690 }
5691
5692 static int
5693 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
5694                       struct osd_idmap_cache *oic)
5695 {
5696         struct lustre_scrub *scrub = &dev->od_scrub.os_scrub;
5697         struct lu_fid *fid = &oic->oic_fid;
5698         struct osd_inode_id *id = &oic->oic_lid;
5699         struct inode *inode = NULL;
5700         int once = 0;
5701         bool insert;
5702         int rc;
5703
5704         ENTRY;
5705
5706         if (!fid_is_norm(fid) && !fid_is_igif(fid))
5707                 RETURN(0);
5708
5709         if (thread_is_running(&scrub->os_thread) &&
5710             scrub->os_pos_current > id->oii_ino)
5711                 RETURN(0);
5712
5713         if (dev->od_auto_scrub_interval == AS_NEVER ||
5714             ktime_get_real_seconds() <
5715             scrub->os_file.sf_time_last_complete + dev->od_auto_scrub_interval)
5716                 RETURN(0);
5717
5718 again:
5719         rc = osd_oi_lookup(oti, dev, fid, &oti->oti_id, 0);
5720         if (rc == -ENOENT) {
5721                 __u32 gen = id->oii_gen;
5722
5723                 insert = true;
5724                 if (inode != NULL)
5725                         goto trigger;
5726
5727                 inode = osd_iget(oti, dev, id);
5728                 /* The inode has been removed (by race maybe). */
5729                 if (IS_ERR(inode)) {
5730                         rc = PTR_ERR(inode);
5731
5732                         RETURN(rc == -ESTALE ? -ENOENT : rc);
5733                 }
5734
5735                 /* The OI mapping is lost. */
5736                 if (gen != OSD_OII_NOGEN)
5737                         goto trigger;
5738
5739                 /*
5740                  * The inode may has been reused by others, we do not know,
5741                  * leave it to be handled by subsequent osd_fid_lookup().
5742                  */
5743                 GOTO(out, rc = 0);
5744         } else if (rc || osd_id_eq(id, &oti->oti_id)) {
5745                 GOTO(out, rc);
5746         }
5747
5748         insert = false;
5749
5750 trigger:
5751         if (thread_is_running(&scrub->os_thread)) {
5752                 if (inode == NULL) {
5753                         inode = osd_iget(oti, dev, id);
5754                         /* The inode has been removed (by race maybe). */
5755                         if (IS_ERR(inode)) {
5756                                 rc = PTR_ERR(inode);
5757
5758                                 RETURN(rc == -ESTALE ? -ENOENT : rc);
5759                         }
5760                 }
5761
5762                 rc = osd_oii_insert(dev, oic, insert);
5763                 /*
5764                  * There is race condition between osd_oi_lookup and OI scrub.
5765                  * The OI scrub finished just after osd_oi_lookup() failure.
5766                  * Under such case, it is unnecessary to trigger OI scrub again,
5767                  * but try to call osd_oi_lookup() again.
5768                  */
5769                 if (unlikely(rc == -EAGAIN))
5770                         goto again;
5771
5772                 if (!S_ISDIR(inode->i_mode))
5773                         rc = 0;
5774                 else
5775                         rc = osd_check_lmv(oti, dev, inode, oic);
5776
5777                 GOTO(out, rc);
5778         }
5779
5780         if (dev->od_auto_scrub_interval != AS_NEVER && ++once == 1) {
5781                 rc = osd_scrub_start(oti->oti_env, dev, SS_AUTO_PARTIAL |
5782                                      SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT);
5783                 CDEBUG(D_LFSCK | D_CONSOLE | D_WARNING,
5784                        "%s: trigger partial OI scrub for RPC inconsistency "
5785                        "checking FID "DFID": rc = %d\n",
5786                        osd_dev2name(dev), PFID(fid), rc);
5787                 if (rc == 0 || rc == -EALREADY)
5788                         goto again;
5789         }
5790
5791         GOTO(out, rc);
5792
5793 out:
5794         if (inode)
5795                 iput(inode);
5796
5797         RETURN(rc);
5798 }
5799
5800 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
5801                                struct osd_device *dev,
5802                                struct osd_idmap_cache *oic,
5803                                struct lu_fid *fid, __u32 ino)
5804 {
5805         struct lustre_ost_attrs *loa = &oti->oti_ost_attrs;
5806         struct inode *inode;
5807         int rc;
5808
5809         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
5810         inode = osd_iget(oti, dev, &oic->oic_lid);
5811         if (IS_ERR(inode)) {
5812                 fid_zero(&oic->oic_fid);
5813                 return PTR_ERR(inode);
5814         }
5815
5816         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, loa);
5817         iput(inode);
5818         if (rc != 0)
5819                 fid_zero(&oic->oic_fid);
5820         else
5821                 *fid = oic->oic_fid = loa->loa_lma.lma_self_fid;
5822         return rc;
5823 }
5824
5825 void osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
5826                       struct osd_inode_id *id, const struct lu_fid *fid)
5827 {
5828         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
5829                id->oii_ino, id->oii_gen, info);
5830         info->oti_cache.oic_lid = *id;
5831         info->oti_cache.oic_fid = *fid;
5832         info->oti_cache.oic_dev = osd;
5833 }
5834
5835 /**
5836  * Get parent FID from the linkEA.
5837  *
5838  * For a directory which parent resides on remote MDT, to satisfy the
5839  * local e2fsck, we insert it into the /REMOTE_PARENT_DIR locally. On
5840  * the other hand, to make the lookup(..) on the directory can return
5841  * the real parent FID, we append the real parent FID after its ".."
5842  * name entry in the /REMOTE_PARENT_DIR.
5843  *
5844  * Unfortunately, such PFID-in-dirent cannot be preserved via file-level
5845  * backup. So after the restore, we cannot get the right parent FID from
5846  * its ".." name entry in the /REMOTE_PARENT_DIR. Under such case, since
5847  * we have stored the real parent FID in the directory object's linkEA,
5848  * we can parse the linkEA for the real parent FID.
5849  *
5850  * \param[in] env       pointer to the thread context
5851  * \param[in] obj       pointer to the object to be handled
5852  * \param[out]fid       pointer to the buffer to hold the parent FID
5853  *
5854  * \retval              0 for getting the real parent FID successfully
5855  * \retval              negative error number on failure
5856  */
5857 static int osd_get_pfid_from_linkea(const struct lu_env *env,
5858                                     struct osd_object *obj,
5859                                     struct lu_fid *fid)
5860 {
5861         struct osd_thread_info *oti = osd_oti_get(env);
5862         struct lu_buf *buf = &oti->oti_big_buf;
5863         struct dentry *dentry = &oti->oti_obj_dentry;
5864         struct inode *inode = obj->oo_inode;
5865         struct linkea_data ldata = { NULL };
5866         int rc;
5867
5868         ENTRY;
5869
5870         fid_zero(fid);
5871         if (!S_ISDIR(inode->i_mode))
5872                 RETURN(-EIO);
5873
5874 again:
5875         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5876                              buf->lb_buf, buf->lb_len);
5877         if (rc == -ERANGE) {
5878                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5879                                      NULL, 0);
5880                 if (rc > 0) {
5881                         lu_buf_realloc(buf, rc);
5882                         if (buf->lb_buf == NULL)
5883                                 RETURN(-ENOMEM);
5884
5885                         goto again;
5886                 }
5887         }
5888
5889         if (unlikely(rc == 0))
5890                 RETURN(-ENODATA);
5891
5892         if (rc < 0)
5893                 RETURN(rc);
5894
5895         if (unlikely(buf->lb_buf == NULL)) {
5896                 lu_buf_realloc(buf, rc);
5897                 if (buf->lb_buf == NULL)
5898                         RETURN(-ENOMEM);
5899
5900                 goto again;
5901         }
5902
5903         ldata.ld_buf = buf;
5904         rc = linkea_init_with_rec(&ldata);
5905         if (!rc) {
5906                 linkea_first_entry(&ldata);
5907                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, NULL, fid);
5908         }
5909
5910         RETURN(rc);
5911 }
5912
5913 static int osd_verify_ent_by_linkea(const struct lu_env *env,
5914                                     struct inode *inode,
5915                                     const struct lu_fid *pfid,
5916                                     const char *name, const int namelen)
5917 {
5918         struct osd_thread_info *oti = osd_oti_get(env);
5919         struct lu_buf *buf = &oti->oti_big_buf;
5920         struct dentry *dentry = &oti->oti_obj_dentry;
5921         struct linkea_data ldata = { NULL };
5922         struct lu_name cname = { .ln_name = name,
5923                                  .ln_namelen = namelen };
5924         int rc;
5925
5926         ENTRY;
5927
5928 again:
5929         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
5930                              buf->lb_buf, buf->lb_len);
5931         if (rc == -ERANGE)
5932                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK, NULL, 0);
5933
5934         if (rc < 0)
5935                 RETURN(rc);
5936
5937         if (unlikely(rc == 0))
5938                 RETURN(-ENODATA);
5939
5940         if (buf->lb_len < rc) {
5941                 lu_buf_realloc(buf, rc);
5942                 if (buf->lb_buf == NULL)
5943                         RETURN(-ENOMEM);
5944
5945                 goto again;
5946         }
5947
5948         ldata.ld_buf = buf;
5949         rc = linkea_init_with_rec(&ldata);
5950         if (!rc)
5951                 rc = linkea_links_find(&ldata, &cname, pfid);
5952
5953         RETURN(rc);
5954 }
5955
5956 /**
5957  * Calls ->lookup() to find dentry. From dentry get inode and
5958  * read inode's ea to get fid. This is required for  interoperability
5959  * mode (b11826)
5960  *
5961  * \retval   0, on success
5962  * \retval -ve, on error
5963  */
5964 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
5965                              struct dt_rec *rec, const struct dt_key *key)
5966 {
5967         struct inode *dir = obj->oo_inode;
5968         struct dentry *dentry;
5969         struct ldiskfs_dir_entry_2 *de;
5970         struct buffer_head *bh;
5971         struct lu_fid *fid = (struct lu_fid *)rec;
5972         struct htree_lock *hlock = NULL;
5973         int ino;
5974         int rc;
5975
5976         ENTRY;
5977
5978         LASSERT(dir->i_op != NULL);
5979         LASSERT(dir->i_op->lookup != NULL);
5980
5981         dentry = osd_child_dentry_get(env, obj,
5982                                       (char *)key, strlen((char *)key));
5983
5984         if (obj->oo_hl_head != NULL) {
5985                 hlock = osd_oti_get(env)->oti_hlock;
5986                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5987                                    dir, LDISKFS_HLOCK_LOOKUP);
5988         } else {
5989                 down_read(&obj->oo_ext_idx_sem);
5990         }
5991
5992         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5993         if (!IS_ERR(bh)) {
5994                 struct osd_thread_info *oti = osd_oti_get(env);
5995                 struct osd_inode_id *id = &oti->oti_id;
5996                 struct osd_idmap_cache *oic = &oti->oti_cache;
5997                 struct osd_device *dev = osd_obj2dev(obj);
5998
5999                 ino = le32_to_cpu(de->inode);
6000                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
6001                         brelse(bh);
6002                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
6003                         GOTO(out, rc);
6004                 }
6005
6006                 rc = osd_get_fid_from_dentry(de, rec);
6007
6008                 /* done with de, release bh */
6009                 brelse(bh);
6010                 if (rc != 0) {
6011                         if (unlikely(is_remote_parent_ino(dev, ino))) {
6012                                 const char *name = (const char *)key;
6013
6014                                 /*
6015                                  * If the parent is on remote MDT, and there
6016                                  * is no FID-in-dirent, then we have to get
6017                                  * the parent FID from the linkEA.
6018                                  */
6019                                 if (likely(strlen(name) == 2 &&
6020                                            name[0] == '.' && name[1] == '.'))
6021                                         rc = osd_get_pfid_from_linkea(env, obj,
6022                                                                       fid);
6023                         } else {
6024                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
6025                         }
6026                 } else {
6027                         osd_id_gen(id, ino, OSD_OII_NOGEN);
6028                 }
6029
6030                 if (rc != 0 || osd_remote_fid(env, dev, fid)) {
6031                         fid_zero(&oic->oic_fid);
6032
6033                         GOTO(out, rc);
6034                 }
6035
6036                 osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id, fid);
6037                 rc = osd_consistency_check(oti, dev, oic);
6038                 if (rc == -ENOENT)
6039                         fid_zero(&oic->oic_fid);
6040                 else
6041                         /* Other error should not affect lookup result. */
6042                         rc = 0;
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                         NULL
7722                 };
7723                 strncat(options, opts, PAGE_SIZE);
7724                 for (rc = 0, str = options; sout[rc]; ) {
7725                         char *op = strstr(str, sout[rc]);
7726
7727                         if (op == NULL) {
7728                                 rc++;
7729                                 str = options;
7730                                 continue;
7731                         }
7732                         if (op == options || *(op - 1) == ',') {
7733                                 str = op + strlen(sout[rc]);
7734                                 if (*str == ',' || *str == '\0') {
7735                                         *str == ',' ? str++ : str;
7736                                         memmove(op, str, strlen(str) + 1);
7737                                 }
7738                         }
7739                         for (str = op; *str != ',' && *str != '\0'; str++)
7740                                 ;
7741                 }
7742         } else {
7743                 strncat(options, "user_xattr,acl", PAGE_SIZE);
7744         }
7745
7746         /* Glom up mount options */
7747         if (*options != '\0')
7748                 strncat(options, ",", PAGE_SIZE);
7749         strncat(options, "no_mbcache,nodelalloc", PAGE_SIZE);
7750
7751         type = get_fs_type("ldiskfs");
7752         if (!type) {
7753                 CERROR("%s: cannot find ldiskfs module\n", name);
7754                 GOTO(out, rc = -ENODEV);
7755         }
7756
7757         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
7758         module_put(type->owner);
7759
7760         if (IS_ERR(o->od_mnt)) {
7761                 rc = PTR_ERR(o->od_mnt);
7762                 o->od_mnt = NULL;
7763                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
7764                 GOTO(out, rc);
7765         }
7766
7767         if (ldiskfs_blocks_count(LDISKFS_SB(osd_sb(o))->s_es) <<
7768                                  osd_sb(o)->s_blocksize_bits > 512ULL << 40 &&
7769                                  force_over_512tb == 0) {
7770                 CERROR("%s: device %s LDISKFS does not support filesystems "
7771                        "greater than 512TB and can cause data corruption. "
7772                        "Use \"force_over_512tb\" mount option to override.\n",
7773                        name, dev);
7774                 GOTO(out_mnt, rc = -EINVAL);
7775         }
7776
7777         if (lmd_flags & LMD_FLG_DEV_RDONLY) {
7778                 if (priv_dev_set_rdonly) {
7779                         priv_dev_set_rdonly(osd_sb(o)->s_bdev);
7780                         o->od_dt_dev.dd_rdonly = 1;
7781                         LCONSOLE_WARN("%s: set dev_rdonly on this device\n",
7782                                       name);
7783                 } else {
7784                         LCONSOLE_WARN("%s: not support dev_rdonly on this device",
7785                                       name);
7786
7787                         GOTO(out_mnt, rc = -EOPNOTSUPP);
7788                 }
7789         } else if (priv_dev_check_rdonly &&
7790                    priv_dev_check_rdonly(osd_sb(o)->s_bdev)) {
7791                 CERROR("%s: underlying device %s is marked as "
7792                        "read-only. Setup failed\n", name, dev);
7793
7794                 GOTO(out_mnt, rc = -EROFS);
7795         }
7796
7797         if (!ldiskfs_has_feature_journal(o->od_mnt->mnt_sb)) {
7798                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
7799                 GOTO(out_mnt, rc = -EINVAL);
7800         }
7801
7802 #ifdef LDISKFS_MOUNT_DIRDATA
7803         if (ldiskfs_has_feature_dirdata(o->od_mnt->mnt_sb))
7804                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
7805         else if (strstr(name, "MDT")) /* don't complain for MGT or OSTs */
7806                 CWARN("%s: device %s was upgraded from Lustre-1.x without "
7807                       "enabling the dirdata feature. If you do not want to "
7808                       "downgrade to Lustre-1.x again, you can enable it via "
7809                       "'tune2fs -O dirdata device'\n", name, dev);
7810 #endif
7811         inode = osd_sb(o)->s_root->d_inode;
7812         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
7813         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
7814         if (rc != 0) {
7815                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
7816                 GOTO(out_mnt, rc);
7817         }
7818
7819         if (lmd_flags & LMD_FLG_NOSCRUB)
7820                 o->od_auto_scrub_interval = AS_NEVER;
7821
7822         if (blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev))) {
7823                 /* do not use pagecache with flash-backed storage */
7824                 o->od_writethrough_cache = 0;
7825                 o->od_read_cache = 0;
7826         }
7827
7828         GOTO(out, rc = 0);
7829
7830 out_mnt:
7831         mntput(o->od_mnt);
7832         o->od_mnt = NULL;
7833
7834 out:
7835         if (__page)
7836                 __free_page(__page);
7837
7838         return rc;
7839 }
7840
7841 static struct lu_device *osd_device_fini(const struct lu_env *env,
7842                                          struct lu_device *d)
7843 {
7844         struct osd_device *o = osd_dev(d);
7845
7846         ENTRY;
7847
7848         osd_index_backup(env, o, false);
7849         osd_shutdown(env, o);
7850         osd_procfs_fini(o);
7851         if (o->od_oi_table != NULL)
7852                 osd_oi_fini(osd_oti_get(env), o);
7853         osd_obj_map_fini(o);
7854         osd_umount(env, o);
7855
7856         RETURN(NULL);
7857 }
7858
7859 static int osd_device_init0(const struct lu_env *env,
7860                             struct osd_device *o,
7861                             struct lustre_cfg *cfg)
7862 {
7863         struct lu_device *l = osd2lu_dev(o);
7864         struct osd_thread_info *info;
7865         int rc;
7866         int cplen = 0;
7867
7868         /* if the module was re-loaded, env can loose its keys */
7869         rc = lu_env_refill((struct lu_env *)env);
7870         if (rc)
7871                 GOTO(out, rc);
7872         info = osd_oti_get(env);
7873         LASSERT(info);
7874
7875         l->ld_ops = &osd_lu_ops;
7876         o->od_dt_dev.dd_ops = &osd_dt_ops;
7877
7878         spin_lock_init(&o->od_osfs_lock);
7879         mutex_init(&o->od_otable_mutex);
7880         INIT_LIST_HEAD(&o->od_orphan_list);
7881         INIT_LIST_HEAD(&o->od_index_backup_list);
7882         INIT_LIST_HEAD(&o->od_index_restore_list);
7883         spin_lock_init(&o->od_lock);
7884         o->od_index_backup_policy = LIBP_NONE;
7885         o->od_t10_type = 0;
7886
7887         o->od_read_cache = 1;
7888         o->od_writethrough_cache = 1;
7889         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
7890
7891         o->od_auto_scrub_interval = AS_DEFAULT;
7892
7893         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
7894                         sizeof(o->od_svname));
7895         if (cplen >= sizeof(o->od_svname)) {
7896                 rc = -E2BIG;
7897                 GOTO(out, rc);
7898         }
7899
7900         o->od_index_backup_stop = 0;
7901         o->od_index = -1; /* -1 means index is invalid */
7902         rc = server_name2index(o->od_svname, &o->od_index, NULL);
7903         if (rc == LDD_F_SV_TYPE_OST)
7904                 o->od_is_ost = 1;
7905
7906         o->od_full_scrub_ratio = OFSR_DEFAULT;
7907         o->od_full_scrub_threshold_rate = FULL_SCRUB_THRESHOLD_RATE_DEFAULT;
7908         rc = osd_mount(env, o, cfg);
7909         if (rc != 0)
7910                 GOTO(out, rc);
7911
7912         /* Can only check block device after mount */
7913         o->od_nonrotational =
7914                 blk_queue_nonrot(bdev_get_queue(osd_sb(o)->s_bdev));
7915
7916         rc = osd_obj_map_init(env, o);
7917         if (rc != 0)
7918                 GOTO(out_mnt, rc);
7919
7920         rc = lu_site_init(&o->od_site, l);
7921         if (rc != 0)
7922                 GOTO(out_compat, rc);
7923         o->od_site.ls_bottom_dev = l;
7924
7925         rc = lu_site_init_finish(&o->od_site);
7926         if (rc != 0)
7927                 GOTO(out_site, rc);
7928
7929         INIT_LIST_HEAD(&o->od_ios_list);
7930         /* setup scrub, including OI files initialization */
7931         o->od_in_init = 1;
7932         rc = osd_scrub_setup(env, o);
7933         o->od_in_init = 0;
7934         if (rc < 0)
7935                 GOTO(out_site, rc);
7936
7937         rc = osd_procfs_init(o, o->od_svname);
7938         if (rc != 0) {
7939                 CERROR("%s: can't initialize procfs: rc = %d\n",
7940                        o->od_svname, rc);
7941                 GOTO(out_scrub, rc);
7942         }
7943
7944         LASSERT(l->ld_site->ls_linkage.next != NULL);
7945         LASSERT(l->ld_site->ls_linkage.prev != NULL);
7946
7947         /* initialize quota slave instance */
7948         /* currently it's no need to prepare qsd_instance_md for OST */
7949         if (!o->od_is_ost) {
7950                 o->od_quota_slave_md = qsd_init(env, o->od_svname,
7951                                                 &o->od_dt_dev,
7952                                                 o->od_proc_entry, true);
7953                 if (IS_ERR(o->od_quota_slave_md)) {
7954                         rc = PTR_ERR(o->od_quota_slave_md);
7955                         o->od_quota_slave_md = NULL;
7956                         GOTO(out_procfs, rc);
7957                 }
7958         }
7959
7960         o->od_quota_slave_dt = qsd_init(env, o->od_svname, &o->od_dt_dev,
7961                                         o->od_proc_entry, false);
7962
7963         if (IS_ERR(o->od_quota_slave_dt)) {
7964                 if (o->od_quota_slave_md != NULL) {
7965                         qsd_fini(env, o->od_quota_slave_md);
7966                         o->od_quota_slave_md = NULL;
7967                 }
7968
7969                 rc = PTR_ERR(o->od_quota_slave_dt);
7970                 o->od_quota_slave_dt = NULL;
7971                 GOTO(out_procfs, rc);
7972         }
7973
7974         RETURN(0);
7975
7976 out_procfs:
7977         osd_procfs_fini(o);
7978 out_scrub:
7979         osd_scrub_cleanup(env, o);
7980 out_site:
7981         lu_site_fini(&o->od_site);
7982 out_compat:
7983         osd_obj_map_fini(o);
7984 out_mnt:
7985         osd_umount(env, o);
7986 out:
7987         return rc;
7988 }
7989
7990 static struct lu_device *osd_device_alloc(const struct lu_env *env,
7991                                           struct lu_device_type *t,
7992                                           struct lustre_cfg *cfg)
7993 {
7994         struct osd_device *o;
7995         int rc;
7996
7997         OBD_ALLOC_PTR(o);
7998         if (o == NULL)
7999                 return ERR_PTR(-ENOMEM);
8000
8001         rc = dt_device_init(&o->od_dt_dev, t);
8002         if (rc == 0) {
8003                 /*
8004                  * Because the ctx might be revived in dt_device_init,
8005                  * refill the env here
8006                  */
8007                 lu_env_refill((struct lu_env *)env);
8008                 rc = osd_device_init0(env, o, cfg);
8009                 if (rc)
8010                         dt_device_fini(&o->od_dt_dev);
8011         }
8012
8013         if (unlikely(rc != 0))
8014                 OBD_FREE_PTR(o);
8015
8016         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
8017 }
8018
8019 static struct lu_device *osd_device_free(const struct lu_env *env,
8020                                          struct lu_device *d)
8021 {
8022         struct osd_device *o = osd_dev(d);
8023
8024         ENTRY;
8025
8026         /* XXX: make osd top device in order to release reference */
8027         d->ld_site->ls_top_dev = d;
8028         lu_site_purge(env, d->ld_site, -1);
8029         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
8030                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
8031                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
8032         }
8033         lu_site_fini(&o->od_site);
8034         dt_device_fini(&o->od_dt_dev);
8035         OBD_FREE_PTR(o);
8036         RETURN(NULL);
8037 }
8038
8039 static int osd_process_config(const struct lu_env *env,
8040                               struct lu_device *d, struct lustre_cfg *cfg)
8041 {
8042         struct osd_device *o = osd_dev(d);
8043         int rc;
8044
8045         ENTRY;
8046
8047         switch (cfg->lcfg_command) {
8048         case LCFG_SETUP:
8049                 rc = osd_mount(env, o, cfg);
8050                 break;
8051         case LCFG_CLEANUP:
8052                 /*
8053                  * For the case LCFG_PRE_CLEANUP is not called in advance,
8054                  * that may happend if hit failure during mount process.
8055                  */
8056                 osd_index_backup(env, o, false);
8057                 lu_dev_del_linkage(d->ld_site, d);
8058                 rc = osd_shutdown(env, o);
8059                 break;
8060         case LCFG_PARAM:
8061                 LASSERT(&o->od_dt_dev);
8062                 rc = class_process_proc_param(PARAM_OSD, lprocfs_osd_obd_vars,
8063                                               cfg, &o->od_dt_dev);
8064                 if (rc > 0 || rc == -ENOSYS) {
8065                         rc = class_process_proc_param(PARAM_OST,
8066                                                       lprocfs_osd_obd_vars,
8067                                                       cfg, &o->od_dt_dev);
8068                         if (rc > 0)
8069                                 rc = 0;
8070                 }
8071                 break;
8072         case LCFG_PRE_CLEANUP:
8073                 osd_scrub_stop(o);
8074                 osd_index_backup(env, o,
8075                                  o->od_index_backup_policy != LIBP_NONE);
8076                 rc = 0;
8077                 break;
8078         default:
8079                 rc = -ENOSYS;
8080         }
8081
8082         RETURN(rc);
8083 }
8084
8085 static int osd_recovery_complete(const struct lu_env *env,
8086                                  struct lu_device *d)
8087 {
8088         struct osd_device *osd = osd_dev(d);
8089         int rc = 0;
8090
8091         ENTRY;
8092
8093         if (osd->od_quota_slave_md == NULL && osd->od_quota_slave_dt == NULL)
8094                 RETURN(0);
8095
8096         /*
8097          * start qsd instance on recovery completion, this notifies the quota
8098          * slave code that we are about to process new requests now
8099          */
8100         rc = qsd_start(env, osd->od_quota_slave_dt);
8101         if (rc == 0 && osd->od_quota_slave_md != NULL)
8102                 rc = qsd_start(env, osd->od_quota_slave_md);
8103
8104         RETURN(rc);
8105 }
8106
8107 /*
8108  * we use exports to track all osd users
8109  */
8110 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
8111                            struct obd_device *obd, struct obd_uuid *cluuid,
8112                            struct obd_connect_data *data, void *localdata)
8113 {
8114         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8115         struct lustre_handle conn;
8116         int rc;
8117
8118         ENTRY;
8119
8120         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
8121
8122         rc = class_connect(&conn, obd, cluuid);
8123         if (rc)
8124                 RETURN(rc);
8125
8126         *exp = class_conn2export(&conn);
8127
8128         spin_lock(&osd->od_osfs_lock);
8129         osd->od_connects++;
8130         spin_unlock(&osd->od_osfs_lock);
8131
8132         RETURN(0);
8133 }
8134
8135 /*
8136  * once last export (we don't count self-export) disappeared
8137  * osd can be released
8138  */
8139 static int osd_obd_disconnect(struct obd_export *exp)
8140 {
8141         struct obd_device *obd = exp->exp_obd;
8142         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8143         int rc, release = 0;
8144
8145         ENTRY;
8146
8147         /* Only disconnect the underlying layers on the final disconnect. */
8148         spin_lock(&osd->od_osfs_lock);
8149         osd->od_connects--;
8150         if (osd->od_connects == 0)
8151                 release = 1;
8152         spin_unlock(&osd->od_osfs_lock);
8153
8154         rc = class_disconnect(exp); /* bz 9811 */
8155
8156         if (rc == 0 && release)
8157                 class_manual_cleanup(obd);
8158         RETURN(rc);
8159 }
8160
8161 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
8162                        struct lu_device *dev)
8163 {
8164         struct osd_device *osd = osd_dev(dev);
8165         struct lr_server_data *lsd =
8166                         &osd->od_dt_dev.dd_lu_dev.ld_site->ls_tgt->lut_lsd;
8167         int result = 0;
8168
8169         ENTRY;
8170
8171         if (osd->od_quota_slave_md != NULL) {
8172                 /* set up quota slave objects for inode */
8173                 result = qsd_prepare(env, osd->od_quota_slave_md);
8174                 if (result != 0)
8175                         RETURN(result);
8176         }
8177
8178         if (osd->od_quota_slave_dt != NULL) {
8179                 /* set up quota slave objects for block */
8180                 result = qsd_prepare(env, osd->od_quota_slave_dt);
8181                 if (result != 0)
8182                         RETURN(result);
8183         }
8184
8185
8186         if (lsd->lsd_feature_incompat & OBD_COMPAT_OST) {
8187 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 52, 0)
8188                 if (lsd->lsd_feature_rocompat & OBD_ROCOMPAT_IDX_IN_IDIF) {
8189                         osd->od_index_in_idif = 1;
8190                 } else {
8191                         osd->od_index_in_idif = 0;
8192                         result = osd_register_proc_index_in_idif(osd);
8193                         if (result != 0)
8194                                 RETURN(result);
8195                 }
8196 #else
8197                 osd->od_index_in_idif = 1;
8198 #endif
8199         }
8200
8201         result = osd_fid_init(env, osd);
8202
8203         RETURN(result);
8204 }
8205
8206 static int osd_fid_alloc(const struct lu_env *env, struct obd_export *exp,
8207                          struct lu_fid *fid, struct md_op_data *op_data)
8208 {
8209         struct osd_device *osd = osd_dev(exp->exp_obd->obd_lu_dev);
8210
8211         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
8212 }
8213
8214 static const struct lu_object_operations osd_lu_obj_ops = {
8215         .loo_object_init      = osd_object_init,
8216         .loo_object_delete    = osd_object_delete,
8217         .loo_object_release   = osd_object_release,
8218         .loo_object_free      = osd_object_free,
8219         .loo_object_print     = osd_object_print,
8220         .loo_object_invariant = osd_object_invariant
8221 };
8222
8223 const struct lu_device_operations osd_lu_ops = {
8224         .ldo_object_alloc      = osd_object_alloc,
8225         .ldo_process_config    = osd_process_config,
8226         .ldo_recovery_complete = osd_recovery_complete,
8227         .ldo_prepare           = osd_prepare,
8228 };
8229
8230 static const struct lu_device_type_operations osd_device_type_ops = {
8231         .ldto_init = osd_type_init,
8232         .ldto_fini = osd_type_fini,
8233
8234         .ldto_start = osd_type_start,
8235         .ldto_stop  = osd_type_stop,
8236
8237         .ldto_device_alloc = osd_device_alloc,
8238         .ldto_device_free  = osd_device_free,
8239
8240         .ldto_device_init = osd_device_init,
8241         .ldto_device_fini = osd_device_fini
8242 };
8243
8244 static struct lu_device_type osd_device_type = {
8245         .ldt_tags     = LU_DEVICE_DT,
8246         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
8247         .ldt_ops      = &osd_device_type_ops,
8248         .ldt_ctx_tags = LCT_LOCAL,
8249 };
8250
8251 static int osd_health_check(const struct lu_env *env, struct obd_device *obd)
8252 {
8253         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
8254         struct super_block *sb = osd_sb(osd);
8255
8256         return (osd->od_mnt == NULL || sb->s_flags & MS_RDONLY);
8257 }
8258
8259 /*
8260  * lprocfs legacy support.
8261  */
8262 static struct obd_ops osd_obd_device_ops = {
8263         .o_owner = THIS_MODULE,
8264         .o_connect      = osd_obd_connect,
8265         .o_disconnect   = osd_obd_disconnect,
8266         .o_fid_alloc    = osd_fid_alloc,
8267         .o_health_check = osd_health_check,
8268 };
8269
8270 static int __init osd_init(void)
8271 {
8272         int rc;
8273
8274         CLASSERT(BH_DXLock < sizeof(((struct buffer_head *)0)->b_state) * 8);
8275 #if !defined(CONFIG_DEBUG_MUTEXES) && !defined(CONFIG_DEBUG_SPINLOCK)
8276         /* please, try to keep osd_thread_info smaller than a page */
8277         CLASSERT(sizeof(struct osd_thread_info) <= PAGE_SIZE);
8278 #endif
8279
8280         osd_oi_mod_init();
8281
8282         rc = lu_kmem_init(ldiskfs_caches);
8283         if (rc)
8284                 return rc;
8285
8286 #ifdef CONFIG_KALLSYMS
8287         priv_dev_set_rdonly = (void *)kallsyms_lookup_name("dev_set_rdonly");
8288         priv_dev_check_rdonly =
8289                 (void *)kallsyms_lookup_name("dev_check_rdonly");
8290 #endif
8291
8292         rc = class_register_type(&osd_obd_device_ops, NULL, true,
8293                                  lprocfs_osd_module_vars,
8294                                  LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
8295         if (rc)
8296                 lu_kmem_fini(ldiskfs_caches);
8297         return rc;
8298 }
8299
8300 static void __exit osd_exit(void)
8301 {
8302         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
8303         lu_kmem_fini(ldiskfs_caches);
8304 }
8305
8306 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
8307 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
8308 MODULE_VERSION(LUSTRE_VERSION_STRING);
8309 MODULE_LICENSE("GPL");
8310
8311 module_init(osd_init);
8312 module_exit(osd_exit);