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