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