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