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