Whamcloud - gitweb
88eed198230c3ec58dfa830912c2a74637db2b1e
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osd/osd_handler.c
37  *
38  * Top-level entry points into osd module
39  *
40  * Author: Nikita Danilov <nikita@clusterfs.com>
41  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
42  */
43
44 #define DEBUG_SUBSYSTEM S_MDS
45
46 #include <linux/module.h>
47
48 /* LUSTRE_VERSION_CODE */
49 #include <lustre_ver.h>
50 /* prerequisite for linux/xattr.h */
51 #include <linux/types.h>
52 /* prerequisite for linux/xattr.h */
53 #include <linux/fs.h>
54 /* XATTR_{REPLACE,CREATE} */
55 #include <linux/xattr.h>
56
57 /*
58  * struct OBD_{ALLOC,FREE}*()
59  * OBD_FAIL_CHECK
60  */
61 #include <obd_support.h>
62 /* struct ptlrpc_thread */
63 #include <lustre_net.h>
64 #include <lustre_fid.h>
65
66 #include "osd_internal.h"
67 #include "osd_dynlocks.h"
68
69 /* llo_* api support */
70 #include <md_object.h>
71 #include <lustre_quota.h>
72
73 int ldiskfs_pdo = 1;
74 CFS_MODULE_PARM(ldiskfs_pdo, "i", int, 0644,
75                 "ldiskfs with parallel directory operations");
76
77 int ldiskfs_track_declares_assert;
78 CFS_MODULE_PARM(ldiskfs_track_declares_assert, "i", int, 0644,
79                 "LBUG during tracking of declares");
80
81 /* Slab to allocate dynlocks */
82 struct kmem_cache *dynlock_cachep;
83
84 static struct lu_kmem_descr ldiskfs_caches[] = {
85         {
86                 .ckd_cache = &dynlock_cachep,
87                 .ckd_name  = "dynlock_cache",
88                 .ckd_size  = sizeof(struct dynlock_handle)
89         },
90         {
91                 .ckd_cache = NULL
92         }
93 };
94
95 static const char dot[] = ".";
96 static const char dotdot[] = "..";
97 static const char remote_obj_dir[] = "REM_OBJ_DIR";
98
99 static const struct lu_object_operations      osd_lu_obj_ops;
100 static const struct dt_object_operations      osd_obj_ops;
101 static const struct dt_object_operations      osd_obj_ea_ops;
102 static const struct dt_object_operations      osd_obj_otable_it_ops;
103 static const struct dt_index_operations       osd_index_iam_ops;
104 static const struct dt_index_operations       osd_index_ea_ops;
105
106 int osd_trans_declare_op2rb[] = {
107         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
108         [OSD_OT_PUNCH]          = OSD_OT_MAX,
109         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
110         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
111         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
112         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
113         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
114         [OSD_OT_WRITE]          = OSD_OT_WRITE,
115         [OSD_OT_INSERT]         = OSD_OT_DELETE,
116         [OSD_OT_DELETE]         = OSD_OT_INSERT,
117         [OSD_OT_UPDATE]         = OSD_OT_MAX,
118         [OSD_OT_QUOTA]          = OSD_OT_MAX,
119 };
120
121 static int osd_has_index(const struct osd_object *obj)
122 {
123         return obj->oo_dt.do_index_ops != NULL;
124 }
125
126 static int osd_object_invariant(const struct lu_object *l)
127 {
128         return osd_invariant(osd_obj(l));
129 }
130
131 /*
132  * Concurrency: doesn't matter
133  */
134 static int osd_read_locked(const struct lu_env *env, struct osd_object *o)
135 {
136         return osd_oti_get(env)->oti_r_locks > 0;
137 }
138
139 /*
140  * Concurrency: doesn't matter
141  */
142 static int osd_write_locked(const struct lu_env *env, struct osd_object *o)
143 {
144         struct osd_thread_info *oti = osd_oti_get(env);
145         return oti->oti_w_locks > 0 && o->oo_owner == env;
146 }
147
148 /*
149  * Concurrency: doesn't access mutable data
150  */
151 static int osd_root_get(const struct lu_env *env,
152                         struct dt_device *dev, struct lu_fid *f)
153 {
154         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
155         return 0;
156 }
157
158 /*
159  * OSD object methods.
160  */
161
162 /*
163  * Concurrency: no concurrent access is possible that early in object
164  * life-cycle.
165  */
166 static struct lu_object *osd_object_alloc(const struct lu_env *env,
167                                           const struct lu_object_header *hdr,
168                                           struct lu_device *d)
169 {
170         struct osd_object *mo;
171
172         OBD_ALLOC_PTR(mo);
173         if (mo != NULL) {
174                 struct lu_object *l;
175
176                 l = &mo->oo_dt.do_lu;
177                 dt_object_init(&mo->oo_dt, NULL, d);
178                 mo->oo_dt.do_ops = &osd_obj_ea_ops;
179                 l->lo_ops = &osd_lu_obj_ops;
180                 init_rwsem(&mo->oo_sem);
181                 init_rwsem(&mo->oo_ext_idx_sem);
182                 spin_lock_init(&mo->oo_guard);
183                 return l;
184         } else {
185                 return NULL;
186         }
187 }
188
189 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
190                 struct dentry *dentry, struct lustre_mdt_attrs *lma)
191 {
192         int rc;
193
194         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
195         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
196                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
197         if (rc > 0) {
198                 if ((void *)lma != (void *)info->oti_mdt_attrs_old)
199                         memcpy(lma, info->oti_mdt_attrs_old, sizeof(*lma));
200                 rc = 0;
201                 lustre_lma_swab(lma);
202                 /* Check LMA compatibility */
203                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
204                         CWARN("%.16s: unsupported incompat LMA feature(s) %#x "
205                               "for fid = "DFID", ino = %lu\n",
206                               LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
207                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
208                               PFID(&lma->lma_self_fid), inode->i_ino);
209                         rc = -EOPNOTSUPP;
210                 }
211         } else if (rc == 0) {
212                 rc = -ENODATA;
213         }
214
215         return rc;
216 }
217
218 /*
219  * retrieve object from backend ext fs.
220  **/
221 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
222                        struct osd_inode_id *id)
223 {
224         struct inode *inode = NULL;
225
226         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
227         if (IS_ERR(inode)) {
228                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
229                        id->oii_ino, PTR_ERR(inode));
230         } else if (id->oii_gen != OSD_OII_NOGEN &&
231                    inode->i_generation != id->oii_gen) {
232                 CDEBUG(D_INODE, "unmatched inode: ino = %u, gen0 = %u, "
233                        "gen1 = %u\n",
234                        id->oii_ino, id->oii_gen, inode->i_generation);
235                 iput(inode);
236                 inode = ERR_PTR(-ESTALE);
237         } else if (inode->i_nlink == 0) {
238                 /* due to parallel readdir and unlink,
239                 * we can have dead inode here. */
240                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
241                 make_bad_inode(inode);
242                 iput(inode);
243                 inode = ERR_PTR(-ESTALE);
244         } else if (is_bad_inode(inode)) {
245                 CWARN("%.16s: bad inode: ino = %u\n",
246                 LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, id->oii_ino);
247                 iput(inode);
248                 inode = ERR_PTR(-ENOENT);
249         } else {
250                 if (id->oii_gen == OSD_OII_NOGEN)
251                         osd_id_gen(id, inode->i_ino, inode->i_generation);
252
253                 /* Do not update file c/mtime in ldiskfs.
254                  * NB: we don't have any lock to protect this because we don't
255                  * have reference on osd_object now, but contention with
256                  * another lookup + attr_set can't happen in the tiny window
257                  * between if (...) and set S_NOCMTIME. */
258                 if (!(inode->i_flags & S_NOCMTIME))
259                         inode->i_flags |= S_NOCMTIME;
260         }
261         return inode;
262 }
263
264 static struct inode *
265 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
266              struct osd_inode_id *id, struct lu_fid *fid)
267 {
268         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
269         struct inode            *inode;
270         int                      rc;
271
272         inode = osd_iget(info, dev, id);
273         if (IS_ERR(inode))
274                 return inode;
275
276         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
277         if (rc == 0) {
278                 *fid = lma->lma_self_fid;
279         } else if (rc == -ENODATA) {
280                 if (unlikely(inode == osd_sb(dev)->s_root->d_inode))
281                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
282                 else
283                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
284         } else {
285                 iput(inode);
286                 inode = ERR_PTR(rc);
287         }
288         return inode;
289 }
290
291 /**
292  * \retval +v: new filter_fid, does not contain self-fid
293  * \retval 0:  filter_fid_old, contains self-fid
294  * \retval -v: other failure cases
295  */
296 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
297                  struct dentry *dentry, struct lu_fid *fid)
298 {
299         struct filter_fid_old   *ff     = &info->oti_ff;
300         struct ost_id           *ostid  = &info->oti_ostid;
301         int                      rc;
302
303         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
304         if (rc == sizeof(*ff)) {
305                 rc = 0;
306                 ostid_set_seq(ostid, le64_to_cpu(ff->ff_seq));
307                 ostid_set_id(ostid, le64_to_cpu(ff->ff_objid));
308                 /* XXX: should use real OST index in the future. LU-3569 */
309                 ostid_to_fid(fid, ostid, 0);
310         } else if (rc == sizeof(struct filter_fid)) {
311                 rc = 1;
312         } else if (rc >= 0) {
313                 rc = -EINVAL;
314         }
315
316         return rc;
317 }
318
319 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
320 {
321         struct osd_thread_info  *info   = osd_oti_get(env);
322         struct osd_device       *osd    = osd_obj2dev(obj);
323         struct lustre_mdt_attrs *lma    = &info->oti_mdt_attrs;
324         struct inode            *inode  = obj->oo_inode;
325         struct dentry           *dentry = &info->oti_obj_dentry;
326         struct lu_fid           *fid    = NULL;
327         int                      rc;
328         ENTRY;
329
330         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_COMPAT_INVALID_ENTRY))
331                 RETURN(0);
332
333         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
334         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
335                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
336         if (rc == -ENODATA && !fid_is_igif(lu_object_fid(&obj->oo_dt.do_lu)) &&
337             osd->od_check_ff) {
338                 fid = &lma->lma_self_fid;
339                 rc = osd_get_idif(info, inode, dentry, fid);
340                 if ((rc > 0) || (rc == -ENODATA && osd->od_lma_self_repair)) {
341                         handle_t *jh;
342
343                         /* For the given OST-object, if it has neither LMA nor
344                          * FID in XATTR_NAME_FID, then the given FID (which is
345                          * contained in the @obj, from client RPC for locating
346                          * the OST-object) is trusted. We use it to generate
347                          * the LMA. */
348
349                         LASSERT(current->journal_info == NULL);
350
351                         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
352                                         osd_dto_credits_noquota[DTO_XATTR_SET]);
353                         if (IS_ERR(jh)) {
354                                 CWARN("%s: cannot start journal for "
355                                       "lma_self_repair: rc = %ld\n",
356                                       osd_name(osd), PTR_ERR(jh));
357                                 RETURN(0);
358                         }
359
360                         rc = osd_ea_fid_set(info, inode,
361                                 lu_object_fid(&obj->oo_dt.do_lu),
362                                 fid_is_on_ost(info, osd,
363                                               lu_object_fid(&obj->oo_dt.do_lu),
364                                               OI_CHECK_FLD) ?
365                                 LMAC_FID_ON_OST : 0, 0);
366                         if (rc != 0)
367                                 CWARN("%s: cannot self repair the LMA: "
368                                       "rc = %d\n", osd_name(osd), rc);
369                         ldiskfs_journal_stop(jh);
370                         RETURN(0);
371                 }
372         }
373
374         if (unlikely(rc == -ENODATA))
375                 RETURN(0);
376
377         if (rc < 0)
378                 RETURN(rc);
379
380         if (rc > 0) {
381                 rc = 0;
382                 lustre_lma_swab(lma);
383                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
384                              CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT))) {
385                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
386                               "fid = "DFID", ino = %lu\n", osd_name(osd),
387                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
388                               PFID(lu_object_fid(&obj->oo_dt.do_lu)),
389                               inode->i_ino);
390                         rc = -EOPNOTSUPP;
391                 } else if (!(lma->lma_compat & LMAC_NOT_IN_OI)) {
392                         fid = &lma->lma_self_fid;
393                 }
394         }
395
396         if (fid != NULL &&
397             unlikely(!lu_fid_eq(lu_object_fid(&obj->oo_dt.do_lu), fid))) {
398                 CDEBUG(D_INODE, "%s: FID "DFID" != self_fid "DFID"\n",
399                        osd_name(osd), PFID(lu_object_fid(&obj->oo_dt.do_lu)),
400                        PFID(&lma->lma_self_fid));
401                 rc = -EREMCHG;
402         }
403
404         RETURN(rc);
405 }
406
407 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
408                           const struct lu_fid *fid,
409                           const struct lu_object_conf *conf)
410 {
411         struct osd_thread_info *info;
412         struct lu_device       *ldev   = obj->oo_dt.do_lu.lo_dev;
413         struct osd_device      *dev;
414         struct osd_idmap_cache *oic;
415         struct osd_inode_id    *id;
416         struct inode           *inode;
417         struct osd_scrub       *scrub;
418         struct scrub_file      *sf;
419         int                     result;
420         int                     saved  = 0;
421         bool                    in_oi  = false;
422         bool                    triggered = false;
423         ENTRY;
424
425         LINVRNT(osd_invariant(obj));
426         LASSERT(obj->oo_inode == NULL);
427         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID, PFID(fid));
428
429         dev = osd_dev(ldev);
430         scrub = &dev->od_scrub;
431         sf = &scrub->os_file;
432         info = osd_oti_get(env);
433         LASSERT(info);
434         oic = &info->oti_cache;
435
436         if (OBD_FAIL_CHECK(OBD_FAIL_OST_ENOENT))
437                 RETURN(-ENOENT);
438
439         /* For the object is created as locking anchor, or for the object to
440          * be created on disk. No need to osd_oi_lookup() at here because FID
441          * shouldn't never be re-used, if it's really a duplicate FID from
442          * unexpected reason, we should be able to detect it later by calling
443          * do_create->osd_oi_insert(). */
444         if (conf != NULL && conf->loc_flags & LOC_F_NEW)
445                 GOTO(out, result = 0);
446
447         /* Search order: 1. per-thread cache. */
448         if (lu_fid_eq(fid, &oic->oic_fid) &&
449             likely(oic->oic_dev == dev)) {
450                 id = &oic->oic_lid;
451                 goto iget;
452         }
453
454         id = &info->oti_id;
455         if (!cfs_list_empty(&scrub->os_inconsistent_items)) {
456                 /* Search order: 2. OI scrub pending list. */
457                 result = osd_oii_lookup(dev, fid, id);
458                 if (result == 0)
459                         goto iget;
460         }
461
462         /* Search order: 3. OI files. */
463         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
464         if (result == -ENOENT) {
465                 if (!fid_is_norm(fid) ||
466                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
467                     !ldiskfs_test_bit(osd_oi_fid2idx(dev,fid),
468                                       sf->sf_oi_bitmap))
469                         GOTO(out, result = 0);
470
471                 goto trigger;
472         }
473
474         if (result != 0)
475                 GOTO(out, result);
476
477         in_oi = true;
478
479 iget:
480         inode = osd_iget(info, dev, id);
481         if (IS_ERR(inode)) {
482                 result = PTR_ERR(inode);
483                 if (result == -ENOENT || result == -ESTALE) {
484                         if (!in_oi) {
485                                 fid_zero(&oic->oic_fid);
486                                 GOTO(out, result = -ENOENT);
487                         }
488
489                         /* XXX: There are three possible cases:
490                          *      1. Backup/restore caused the OI invalid.
491                          *      2. Someone unlinked the object but NOT removed
492                          *         the OI mapping, such as mount target device
493                          *         as ldiskfs, and modify something directly.
494                          *      3. Someone just removed the object between the
495                          *         former oi_lookup and the iget. It is normal.
496                          *
497                          *      It is diffcult to distinguish the 2nd from the
498                          *      1st case. Relatively speaking, the 1st case is
499                          *      common than the 2nd case, trigger OI scrub. */
500                         result = osd_oi_lookup(info, dev, fid, id, true);
501                         if (result == 0)
502                                 /* It is the case 1 or 2. */
503                                 goto trigger;
504                 } else if (result == -EREMCHG) {
505
506 trigger:
507                         if (unlikely(triggered))
508                                 GOTO(out, result = saved);
509
510                         triggered = true;
511                         if (thread_is_running(&scrub->os_thread)) {
512                                 result = -EINPROGRESS;
513                         } else if (!dev->od_noscrub) {
514                                 result = osd_scrub_start(dev);
515                                 LCONSOLE_ERROR("%.16s: trigger OI scrub by RPC "
516                                                "for "DFID", rc = %d [1]\n",
517                                                LDISKFS_SB(osd_sb(dev))->s_es->\
518                                                s_volume_name,PFID(fid), result);
519                                 if (result == 0 || result == -EALREADY)
520                                         result = -EINPROGRESS;
521                                 else
522                                         result = -EREMCHG;
523                         }
524
525                         /* We still have chance to get the valid inode: for the
526                          * object which is referenced by remote name entry, the
527                          * object on the local MDT will be linked under the dir
528                          * of "/REMOTE_PARENT_DIR" with its FID string as name.
529                          *
530                          * We do not know whether the object for the given FID
531                          * is referenced by some remote name entry or not, and
532                          * especially for DNE II, a multiple-linked object may
533                          * have many name entries reside on many MDTs.
534                          *
535                          * To simplify the operation, OSD will not distinguish
536                          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
537                          * only happened for the RPC from other MDT during the
538                          * OI scrub, or for the client side RPC with FID only,
539                          * such as FID to path, or from old connected client. */
540                         saved = result;
541                         result = osd_lookup_in_remote_parent(info, dev,
542                                                              fid, id);
543                         if (result == 0) {
544                                 in_oi = false;
545                                 goto iget;
546                         }
547
548                         result = saved;
549                 }
550
551                 GOTO(out, result);
552         }
553
554         obj->oo_inode = inode;
555         LASSERT(obj->oo_inode->i_sb == osd_sb(dev));
556
557         result = osd_check_lma(env, obj);
558         if (result != 0) {
559                 iput(inode);
560                 obj->oo_inode = NULL;
561                 if (result == -EREMCHG)
562                         goto trigger;
563
564                 GOTO(out, result);
565         }
566
567         obj->oo_compat_dot_created = 1;
568         obj->oo_compat_dotdot_created = 1;
569
570         if (!S_ISDIR(inode->i_mode) || !ldiskfs_pdo) /* done */
571                 GOTO(out, result = 0);
572
573         LASSERT(obj->oo_hl_head == NULL);
574         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
575         if (obj->oo_hl_head == NULL) {
576                 obj->oo_inode = NULL;
577                 iput(inode);
578                 GOTO(out, result = -ENOMEM);
579         }
580         GOTO(out, result = 0);
581
582 out:
583         LINVRNT(osd_invariant(obj));
584         return result;
585 }
586
587 /*
588  * Concurrency: shouldn't matter.
589  */
590 static void osd_object_init0(struct osd_object *obj)
591 {
592         LASSERT(obj->oo_inode != NULL);
593         obj->oo_dt.do_body_ops = &osd_body_ops;
594         obj->oo_dt.do_lu.lo_header->loh_attr |=
595                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
596 }
597
598 /*
599  * Concurrency: no concurrent access is possible that early in object
600  * life-cycle.
601  */
602 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
603                            const struct lu_object_conf *conf)
604 {
605         struct osd_object *obj = osd_obj(l);
606         int result;
607
608         LINVRNT(osd_invariant(obj));
609
610         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
611                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
612                 l->lo_header->loh_attr |= LOHA_EXISTS;
613                 return 0;
614         }
615
616         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
617         obj->oo_dt.do_body_ops = &osd_body_ops_new;
618         if (result == 0 && obj->oo_inode != NULL)
619                 osd_object_init0(obj);
620
621         LINVRNT(osd_invariant(obj));
622         return result;
623 }
624
625 /*
626  * Concurrency: no concurrent access is possible that late in object
627  * life-cycle.
628  */
629 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
630 {
631         struct osd_object *obj = osd_obj(l);
632
633         LINVRNT(osd_invariant(obj));
634
635         dt_object_fini(&obj->oo_dt);
636         if (obj->oo_hl_head != NULL)
637                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
638         OBD_FREE_PTR(obj);
639 }
640
641 /*
642  * Concurrency: no concurrent access is possible that late in object
643  * life-cycle.
644  */
645 static void osd_index_fini(struct osd_object *o)
646 {
647         struct iam_container *bag;
648
649         if (o->oo_dir != NULL) {
650                 bag = &o->oo_dir->od_container;
651                 if (o->oo_inode != NULL) {
652                         if (bag->ic_object == o->oo_inode)
653                                 iam_container_fini(bag);
654                 }
655                 OBD_FREE_PTR(o->oo_dir);
656                 o->oo_dir = NULL;
657         }
658 }
659
660 /*
661  * Concurrency: no concurrent access is possible that late in object
662  * life-cycle (for all existing callers, that is. New callers have to provide
663  * their own locking.)
664  */
665 static int osd_inode_unlinked(const struct inode *inode)
666 {
667         return inode->i_nlink == 0;
668 }
669
670 enum {
671         OSD_TXN_OI_DELETE_CREDITS    = 20,
672         OSD_TXN_INODE_DELETE_CREDITS = 20
673 };
674
675 /*
676  * Journal
677  */
678
679 #if OSD_THANDLE_STATS
680 /**
681  * Set time when the handle is allocated
682  */
683 static void osd_th_alloced(struct osd_thandle *oth)
684 {
685         oth->oth_alloced = cfs_time_current();
686 }
687
688 /**
689  * Set time when the handle started
690  */
691 static void osd_th_started(struct osd_thandle *oth)
692 {
693         oth->oth_started = cfs_time_current();
694 }
695
696 /**
697  * Helper function to convert time interval to microseconds packed in
698  * long int.
699  */
700 static long interval_to_usec(cfs_time_t start, cfs_time_t end)
701 {
702         struct timeval val;
703
704         cfs_duration_usec(cfs_time_sub(end, start), &val);
705         return val.tv_sec * 1000000 + val.tv_usec;
706 }
707
708 /**
709  * Check whether the we deal with this handle for too long.
710  */
711 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
712                                 cfs_time_t alloced, cfs_time_t started,
713                                 cfs_time_t closed)
714 {
715         cfs_time_t now = cfs_time_current();
716
717         LASSERT(dev != NULL);
718
719         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
720                             interval_to_usec(alloced, started));
721         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
722                             interval_to_usec(started, closed));
723         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
724                             interval_to_usec(closed, now));
725
726         if (cfs_time_before(cfs_time_add(alloced, cfs_time_seconds(30)), now)) {
727                 CWARN("transaction handle %p was open for too long: "
728                       "now "CFS_TIME_T" ,"
729                       "alloced "CFS_TIME_T" ,"
730                       "started "CFS_TIME_T" ,"
731                       "closed "CFS_TIME_T"\n",
732                       oth, now, alloced, started, closed);
733                 libcfs_debug_dumpstack(NULL);
734         }
735 }
736
737 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
738 {                                                                       \
739         cfs_time_t __closed = cfs_time_current();                       \
740         cfs_time_t __alloced = oth->oth_alloced;                        \
741         cfs_time_t __started = oth->oth_started;                        \
742                                                                         \
743         expr;                                                           \
744         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
745 }
746
747 #else /* OSD_THANDLE_STATS */
748
749 #define osd_th_alloced(h)                  do {} while(0)
750 #define osd_th_started(h)                  do {} while(0)
751 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
752
753 #endif /* OSD_THANDLE_STATS */
754
755 /*
756  * Concurrency: doesn't access mutable data.
757  */
758 static int osd_param_is_not_sane(const struct osd_device *dev,
759                                  const struct thandle *th)
760 {
761         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
762
763         return oh->ot_credits > osd_journal(dev)->j_max_transaction_buffers;
764 }
765
766 /*
767  * Concurrency: shouldn't matter.
768  */
769 static void osd_trans_commit_cb(struct super_block *sb,
770                                 struct ldiskfs_journal_cb_entry *jcb, int error)
771 {
772         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
773         struct thandle     *th  = &oh->ot_super;
774         struct lu_device   *lud = &th->th_dev->dd_lu_dev;
775         struct dt_txn_commit_cb *dcb, *tmp;
776
777         LASSERT(oh->ot_handle == NULL);
778
779         if (error)
780                 CERROR("transaction @0x%p commit error: %d\n", th, error);
781
782         dt_txn_hook_commit(th);
783
784         /* call per-transaction callbacks if any */
785         cfs_list_for_each_entry_safe(dcb, tmp, &oh->ot_dcb_list, dcb_linkage) {
786                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
787                          "commit callback entry: magic=%x name='%s'\n",
788                          dcb->dcb_magic, dcb->dcb_name);
789                 cfs_list_del_init(&dcb->dcb_linkage);
790                 dcb->dcb_func(NULL, th, dcb, error);
791         }
792
793         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
794         lu_device_put(lud);
795         th->th_dev = NULL;
796
797         lu_context_exit(&th->th_ctx);
798         lu_context_fini(&th->th_ctx);
799         OBD_FREE_PTR(oh);
800 }
801
802 static struct thandle *osd_trans_create(const struct lu_env *env,
803                                         struct dt_device *d)
804 {
805         struct osd_thread_info *oti = osd_oti_get(env);
806         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
807         struct osd_thandle     *oh;
808         struct thandle         *th;
809         ENTRY;
810
811         /* on pending IO in this thread should left from prev. request */
812         LASSERT(cfs_atomic_read(&iobuf->dr_numreqs) == 0);
813
814         th = ERR_PTR(-ENOMEM);
815         OBD_ALLOC_GFP(oh, sizeof *oh, __GFP_IO);
816         if (oh != NULL) {
817                 oh->ot_quota_trans = &oti->oti_quota_trans;
818                 memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
819                 th = &oh->ot_super;
820                 th->th_dev = d;
821                 th->th_result = 0;
822                 th->th_tags = LCT_TX_HANDLE;
823                 oh->ot_credits = 0;
824                 oti->oti_dev = osd_dt_dev(d);
825                 CFS_INIT_LIST_HEAD(&oh->ot_dcb_list);
826                 osd_th_alloced(oh);
827
828                 memset(oti->oti_declare_ops, 0,
829                                         sizeof(oti->oti_declare_ops));
830                 memset(oti->oti_declare_ops_rb, 0,
831                                         sizeof(oti->oti_declare_ops_rb));
832                 memset(oti->oti_declare_ops_cred, 0,
833                                         sizeof(oti->oti_declare_ops_cred));
834                 oti->oti_rollback = false;
835         }
836         RETURN(th);
837 }
838
839 /*
840  * Concurrency: shouldn't matter.
841  */
842 int osd_trans_start(const struct lu_env *env, struct dt_device *d,
843                     struct thandle *th)
844 {
845         struct osd_thread_info *oti = osd_oti_get(env);
846         struct osd_device  *dev = osd_dt_dev(d);
847         handle_t           *jh;
848         struct osd_thandle *oh;
849         int rc;
850
851         ENTRY;
852
853         LASSERT(current->journal_info == NULL);
854
855         oh = container_of0(th, struct osd_thandle, ot_super);
856         LASSERT(oh != NULL);
857         LASSERT(oh->ot_handle == NULL);
858
859         rc = dt_txn_hook_start(env, d, th);
860         if (rc != 0)
861                 GOTO(out, rc);
862
863         if (unlikely(osd_param_is_not_sane(dev, th))) {
864                 static unsigned long last_printed;
865                 static int last_credits;
866
867                 CWARN("%.16s: too many transaction credits (%d > %d)\n",
868                       LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
869                       oh->ot_credits,
870                       osd_journal(dev)->j_max_transaction_buffers);
871                 CWARN("  create: %u/%u, delete: %u/%u, destroy: %u/%u\n",
872                       oti->oti_declare_ops[OSD_OT_CREATE],
873                       oti->oti_declare_ops_cred[OSD_OT_CREATE],
874                       oti->oti_declare_ops[OSD_OT_DELETE],
875                       oti->oti_declare_ops_cred[OSD_OT_DELETE],
876                       oti->oti_declare_ops[OSD_OT_DESTROY],
877                       oti->oti_declare_ops_cred[OSD_OT_DESTROY]);
878                 CWARN("  attr_set: %u/%u, xattr_set: %u/%u\n",
879                       oti->oti_declare_ops[OSD_OT_ATTR_SET],
880                       oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
881                       oti->oti_declare_ops[OSD_OT_XATTR_SET],
882                       oti->oti_declare_ops_cred[OSD_OT_XATTR_SET]);
883                 CWARN("  write: %u/%u, punch: %u/%u, quota %u/%u\n",
884                       oti->oti_declare_ops[OSD_OT_WRITE],
885                       oti->oti_declare_ops_cred[OSD_OT_WRITE],
886                       oti->oti_declare_ops[OSD_OT_PUNCH],
887                       oti->oti_declare_ops_cred[OSD_OT_PUNCH],
888                       oti->oti_declare_ops[OSD_OT_QUOTA],
889                       oti->oti_declare_ops_cred[OSD_OT_QUOTA]);
890                 CWARN("  insert: %u/%u, delete: %u/%u\n",
891                       oti->oti_declare_ops[OSD_OT_INSERT],
892                       oti->oti_declare_ops_cred[OSD_OT_INSERT],
893                       oti->oti_declare_ops[OSD_OT_DESTROY],
894                       oti->oti_declare_ops_cred[OSD_OT_DESTROY]);
895                 CWARN("  ref_add: %u/%u, ref_del: %u/%u\n",
896                       oti->oti_declare_ops[OSD_OT_REF_ADD],
897                       oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
898                       oti->oti_declare_ops[OSD_OT_REF_DEL],
899                       oti->oti_declare_ops_cred[OSD_OT_REF_DEL]);
900
901                 if (last_credits != oh->ot_credits &&
902                     time_after(jiffies, last_printed + 60 * HZ)) {
903                         libcfs_debug_dumpstack(NULL);
904                         last_credits = oh->ot_credits;
905                         last_printed = jiffies;
906                 }
907                 /* XXX Limit the credits to 'max_transaction_buffers', and
908                  *     let the underlying filesystem to catch the error if
909                  *     we really need so many credits.
910                  *
911                  *     This should be removed when we can calculate the
912                  *     credits precisely. */
913                 oh->ot_credits = osd_journal(dev)->j_max_transaction_buffers;
914         }
915
916         /*
917          * XXX temporary stuff. Some abstraction layer should
918          * be used.
919          */
920         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
921         osd_th_started(oh);
922         if (!IS_ERR(jh)) {
923                 oh->ot_handle = jh;
924                 LASSERT(oti->oti_txns == 0);
925                 lu_context_init(&th->th_ctx, th->th_tags);
926                 lu_context_enter(&th->th_ctx);
927
928                 lu_device_get(&d->dd_lu_dev);
929                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
930                               "osd-tx", th);
931                 oti->oti_txns++;
932                 rc = 0;
933         } else {
934                 rc = PTR_ERR(jh);
935         }
936 out:
937         RETURN(rc);
938 }
939
940 /*
941  * Concurrency: shouldn't matter.
942  */
943 static int osd_trans_stop(const struct lu_env *env, struct thandle *th)
944 {
945         int                     rc = 0;
946         struct osd_thandle     *oh;
947         struct osd_thread_info *oti = osd_oti_get(env);
948         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
949         struct qsd_instance    *qsd = oti->oti_dev->od_quota_slave;
950         ENTRY;
951
952         oh = container_of0(th, struct osd_thandle, ot_super);
953
954         if (qsd != NULL)
955                 /* inform the quota slave device that the transaction is
956                  * stopping */
957                 qsd_op_end(env, qsd, oh->ot_quota_trans);
958         oh->ot_quota_trans = NULL;
959
960         if (oh->ot_handle != NULL) {
961                 handle_t *hdl = oh->ot_handle;
962
963                 /*
964                  * add commit callback
965                  * notice we don't do this in osd_trans_start()
966                  * as underlying transaction can change during truncate
967                  */
968                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
969                                          &oh->ot_jcb);
970
971                 LASSERT(oti->oti_txns == 1);
972                 oti->oti_txns--;
973                 rc = dt_txn_hook_stop(env, th);
974                 if (rc != 0)
975                         CERROR("Failure in transaction hook: %d\n", rc);
976
977                 /* hook functions might modify th_sync */
978                 hdl->h_sync = th->th_sync;
979
980                 oh->ot_handle = NULL;
981                 OSD_CHECK_SLOW_TH(oh, oti->oti_dev,
982                                   rc = ldiskfs_journal_stop(hdl));
983                 if (rc != 0)
984                         CERROR("Failure to stop transaction: %d\n", rc);
985         } else {
986                 OBD_FREE_PTR(oh);
987         }
988
989         /* as we want IO to journal and data IO be concurrent, we don't block
990          * awaiting data IO completion in osd_do_bio(), instead we wait here
991          * once transaction is submitted to the journal. all reqular requests
992          * don't do direct IO (except read/write), thus this wait_event becomes
993          * no-op for them.
994          *
995          * IMPORTANT: we have to wait till any IO submited by the thread is
996          * completed otherwise iobuf may be corrupted by different request
997          */
998         wait_event(iobuf->dr_wait,
999                        cfs_atomic_read(&iobuf->dr_numreqs) == 0);
1000         if (!rc)
1001                 rc = iobuf->dr_error;
1002
1003         RETURN(rc);
1004 }
1005
1006 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
1007 {
1008         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
1009                                                ot_super);
1010
1011         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
1012         LASSERT(&dcb->dcb_func != NULL);
1013         cfs_list_add(&dcb->dcb_linkage, &oh->ot_dcb_list);
1014
1015         return 0;
1016 }
1017
1018 /*
1019  * Called just before object is freed. Releases all resources except for
1020  * object itself (that is released by osd_object_free()).
1021  *
1022  * Concurrency: no concurrent access is possible that late in object
1023  * life-cycle.
1024  */
1025 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
1026 {
1027         struct osd_object *obj   = osd_obj(l);
1028         struct inode      *inode = obj->oo_inode;
1029
1030         LINVRNT(osd_invariant(obj));
1031
1032         /*
1033          * If object is unlinked remove fid->ino mapping from object index.
1034          */
1035
1036         osd_index_fini(obj);
1037         if (inode != NULL) {
1038                 struct qsd_instance     *qsd = osd_obj2dev(obj)->od_quota_slave;
1039                 qid_t                    uid = inode->i_uid;
1040                 qid_t                    gid = inode->i_gid;
1041
1042                 iput(inode);
1043                 obj->oo_inode = NULL;
1044
1045                 if (qsd != NULL) {
1046                         struct osd_thread_info  *info = osd_oti_get(env);
1047                         struct lquota_id_info   *qi = &info->oti_qi;
1048
1049                         /* Release granted quota to master if necessary */
1050                         qi->lqi_id.qid_uid = uid;
1051                         qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
1052
1053                         qi->lqi_id.qid_uid = gid;
1054                         qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
1055                 }
1056         }
1057 }
1058
1059 /*
1060  * Concurrency: ->loo_object_release() is called under site spin-lock.
1061  */
1062 static void osd_object_release(const struct lu_env *env,
1063                                struct lu_object *l)
1064 {
1065 }
1066
1067 /*
1068  * Concurrency: shouldn't matter.
1069  */
1070 static int osd_object_print(const struct lu_env *env, void *cookie,
1071                             lu_printer_t p, const struct lu_object *l)
1072 {
1073         struct osd_object *o = osd_obj(l);
1074         struct iam_descr  *d;
1075
1076         if (o->oo_dir != NULL)
1077                 d = o->oo_dir->od_container.ic_descr;
1078         else
1079                 d = NULL;
1080         return (*p)(env, cookie,
1081                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
1082                     o, o->oo_inode,
1083                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
1084                     o->oo_inode ? o->oo_inode->i_generation : 0,
1085                     d ? d->id_ops->id_name : "plain");
1086 }
1087
1088 /*
1089  * Concurrency: shouldn't matter.
1090  */
1091 int osd_statfs(const struct lu_env *env, struct dt_device *d,
1092                struct obd_statfs *sfs)
1093 {
1094         struct osd_device  *osd = osd_dt_dev(d);
1095         struct super_block *sb = osd_sb(osd);
1096         struct kstatfs     *ksfs;
1097         int result = 0;
1098
1099         if (unlikely(osd->od_mnt == NULL))
1100                 return -EINPROGRESS;
1101
1102         /* osd_lproc.c call this without env, allocate ksfs for that case */
1103         if (unlikely(env == NULL)) {
1104                 OBD_ALLOC_PTR(ksfs);
1105                 if (ksfs == NULL)
1106                         return -ENOMEM;
1107         } else {
1108                 ksfs = &osd_oti_get(env)->oti_ksfs;
1109         }
1110
1111         spin_lock(&osd->od_osfs_lock);
1112         /* cache 1 second */
1113         if (cfs_time_before_64(osd->od_osfs_age, cfs_time_shift_64(-1))) {
1114                 result = sb->s_op->statfs(sb->s_root, ksfs);
1115                 if (likely(result == 0)) { /* N.B. statfs can't really fail */
1116                         osd->od_osfs_age = cfs_time_current_64();
1117                         statfs_pack(&osd->od_statfs, ksfs);
1118                         if (sb->s_flags & MS_RDONLY)
1119                                 sfs->os_state = OS_STATE_READONLY;
1120                 }
1121         }
1122
1123         if (likely(result == 0))
1124                 *sfs = osd->od_statfs;
1125         spin_unlock(&osd->od_osfs_lock);
1126
1127         if (unlikely(env == NULL))
1128                 OBD_FREE_PTR(ksfs);
1129
1130         return result;
1131 }
1132
1133 /**
1134  * Estimate space needed for file creations. We assume the largest filename
1135  * which is 2^64 - 1, hence a filename of 20 chars.
1136  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
1137  */
1138 #ifdef __LDISKFS_DIR_REC_LEN
1139 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
1140 #else
1141 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
1142 #endif
1143
1144 /*
1145  * Concurrency: doesn't access mutable data.
1146  */
1147 static void osd_conf_get(const struct lu_env *env,
1148                          const struct dt_device *dev,
1149                          struct dt_device_param *param)
1150 {
1151         struct super_block *sb = osd_sb(osd_dt_dev(dev));
1152
1153         /*
1154          * XXX should be taken from not-yet-existing fs abstraction layer.
1155          */
1156         param->ddp_max_name_len = LDISKFS_NAME_LEN;
1157         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
1158         param->ddp_block_shift  = sb->s_blocksize_bits;
1159         param->ddp_mount_type     = LDD_MT_LDISKFS;
1160         param->ddp_maxbytes       = sb->s_maxbytes;
1161         /* Overhead estimate should be fairly accurate, so we really take a tiny
1162          * error margin which also avoids fragmenting the filesystem too much */
1163         param->ddp_grant_reserved = 2; /* end up to be 1.9% after conversion */
1164         /* inode are statically allocated, so per-inode space consumption
1165          * is the space consumed by the directory entry */
1166         param->ddp_inodespace     = PER_OBJ_USAGE;
1167         /* per-fragment overhead to be used by the client code */
1168         param->ddp_grant_frag     = 6 * LDISKFS_BLOCK_SIZE(sb);
1169         param->ddp_mntopts      = 0;
1170         if (test_opt(sb, XATTR_USER))
1171                 param->ddp_mntopts |= MNTOPT_USERXATTR;
1172         if (test_opt(sb, POSIX_ACL))
1173                 param->ddp_mntopts |= MNTOPT_ACL;
1174
1175 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
1176         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EA_INODE))
1177                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE;
1178         else
1179 #endif
1180                 param->ddp_max_ea_size = sb->s_blocksize;
1181
1182 }
1183
1184 /*
1185  * Concurrency: shouldn't matter.
1186  */
1187 static int osd_sync(const struct lu_env *env, struct dt_device *d)
1188 {
1189         CDEBUG(D_HA, "syncing OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1190         return ldiskfs_force_commit(osd_sb(osd_dt_dev(d)));
1191 }
1192
1193 /**
1194  * Start commit for OSD device.
1195  *
1196  * An implementation of dt_commit_async method for OSD device.
1197  * Asychronously starts underlayng fs sync and thereby a transaction
1198  * commit.
1199  *
1200  * \param env environment
1201  * \param d dt device
1202  *
1203  * \see dt_device_operations
1204  */
1205 static int osd_commit_async(const struct lu_env *env,
1206                             struct dt_device *d)
1207 {
1208         struct super_block *s = osd_sb(osd_dt_dev(d));
1209         ENTRY;
1210
1211         CDEBUG(D_HA, "async commit OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1212         RETURN(s->s_op->sync_fs(s, 0));
1213 }
1214
1215 /*
1216  * Concurrency: shouldn't matter.
1217  */
1218
1219 static int osd_ro(const struct lu_env *env, struct dt_device *d)
1220 {
1221         struct super_block *sb = osd_sb(osd_dt_dev(d));
1222         struct block_device *dev = sb->s_bdev;
1223 #ifdef HAVE_DEV_SET_RDONLY
1224         struct block_device *jdev = LDISKFS_SB(sb)->journal_bdev;
1225         int rc = 0;
1226 #else
1227         int rc = -EOPNOTSUPP;
1228 #endif
1229         ENTRY;
1230
1231 #ifdef HAVE_DEV_SET_RDONLY
1232         CERROR("*** setting %s read-only ***\n", osd_dt_dev(d)->od_svname);
1233
1234         if (jdev && (jdev != dev)) {
1235                 CDEBUG(D_IOCTL | D_HA, "set journal dev %lx rdonly\n",
1236                        (long)jdev);
1237                 dev_set_rdonly(jdev);
1238         }
1239         CDEBUG(D_IOCTL | D_HA, "set dev %lx rdonly\n", (long)dev);
1240         dev_set_rdonly(dev);
1241 #else
1242         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
1243                osd_dt_dev(d)->od_svname, (long)dev, rc);
1244 #endif
1245         RETURN(rc);
1246 }
1247
1248 /*
1249  * Concurrency: serialization provided by callers.
1250  */
1251 static int osd_init_capa_ctxt(const struct lu_env *env, struct dt_device *d,
1252                               int mode, unsigned long timeout, __u32 alg,
1253                               struct lustre_capa_key *keys)
1254 {
1255         struct osd_device *dev = osd_dt_dev(d);
1256         ENTRY;
1257
1258         dev->od_fl_capa = mode;
1259         dev->od_capa_timeout = timeout;
1260         dev->od_capa_alg = alg;
1261         dev->od_capa_keys = keys;
1262         RETURN(0);
1263 }
1264
1265 /**
1266  * Note: we do not count into QUOTA here.
1267  * If we mount with --data_journal we may need more.
1268  */
1269 const int osd_dto_credits_noquota[DTO_NR] = {
1270         /**
1271          * Insert/Delete.
1272          * INDEX_EXTRA_TRANS_BLOCKS(8) +
1273          * SINGLEDATA_TRANS_BLOCKS(8)
1274          * XXX Note: maybe iam need more, since iam have more level than
1275          *           EXT3 htree.
1276          */
1277         [DTO_INDEX_INSERT]  = 16,
1278         [DTO_INDEX_DELETE]  = 16,
1279         /**
1280          * Used for OI scrub
1281          */
1282         [DTO_INDEX_UPDATE]  = 16,
1283         /**
1284          * Create a object. The same as create object in EXT3.
1285          * DATA_TRANS_BLOCKS(14) +
1286          * INDEX_EXTRA_BLOCKS(8) +
1287          * 3(inode bits, groups, GDT)
1288          */
1289         [DTO_OBJECT_CREATE] = 25,
1290         /**
1291          * XXX: real credits to be fixed
1292          */
1293         [DTO_OBJECT_DELETE] = 25,
1294         /**
1295          * Attr set credits (inode)
1296          */
1297         [DTO_ATTR_SET_BASE] = 1,
1298         /**
1299          * Xattr set. The same as xattr of EXT3.
1300          * DATA_TRANS_BLOCKS(14)
1301          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
1302          * are also counted in. Do not know why?
1303          */
1304         [DTO_XATTR_SET]     = 14,
1305         [DTO_LOG_REC]       = 14,
1306         /**
1307          * credits for inode change during write.
1308          */
1309         [DTO_WRITE_BASE]    = 3,
1310         /**
1311          * credits for single block write.
1312          */
1313         [DTO_WRITE_BLOCK]   = 14,
1314         /**
1315          * Attr set credits for chown.
1316          * This is extra credits for setattr, and it is null without quota
1317          */
1318         [DTO_ATTR_SET_CHOWN]= 0
1319 };
1320
1321 static const struct dt_device_operations osd_dt_ops = {
1322         .dt_root_get       = osd_root_get,
1323         .dt_statfs         = osd_statfs,
1324         .dt_trans_create   = osd_trans_create,
1325         .dt_trans_start    = osd_trans_start,
1326         .dt_trans_stop     = osd_trans_stop,
1327         .dt_trans_cb_add   = osd_trans_cb_add,
1328         .dt_conf_get       = osd_conf_get,
1329         .dt_sync           = osd_sync,
1330         .dt_ro             = osd_ro,
1331         .dt_commit_async   = osd_commit_async,
1332         .dt_init_capa_ctxt = osd_init_capa_ctxt,
1333 };
1334
1335 static void osd_object_read_lock(const struct lu_env *env,
1336                                  struct dt_object *dt, unsigned role)
1337 {
1338         struct osd_object *obj = osd_dt_obj(dt);
1339         struct osd_thread_info *oti = osd_oti_get(env);
1340
1341         LINVRNT(osd_invariant(obj));
1342
1343         LASSERT(obj->oo_owner != env);
1344         down_read_nested(&obj->oo_sem, role);
1345
1346         LASSERT(obj->oo_owner == NULL);
1347         oti->oti_r_locks++;
1348 }
1349
1350 static void osd_object_write_lock(const struct lu_env *env,
1351                                   struct dt_object *dt, unsigned role)
1352 {
1353         struct osd_object *obj = osd_dt_obj(dt);
1354         struct osd_thread_info *oti = osd_oti_get(env);
1355
1356         LINVRNT(osd_invariant(obj));
1357
1358         LASSERT(obj->oo_owner != env);
1359         down_write_nested(&obj->oo_sem, role);
1360
1361         LASSERT(obj->oo_owner == NULL);
1362         obj->oo_owner = env;
1363         oti->oti_w_locks++;
1364 }
1365
1366 static void osd_object_read_unlock(const struct lu_env *env,
1367                                    struct dt_object *dt)
1368 {
1369         struct osd_object *obj = osd_dt_obj(dt);
1370         struct osd_thread_info *oti = osd_oti_get(env);
1371
1372         LINVRNT(osd_invariant(obj));
1373
1374         LASSERT(oti->oti_r_locks > 0);
1375         oti->oti_r_locks--;
1376         up_read(&obj->oo_sem);
1377 }
1378
1379 static void osd_object_write_unlock(const struct lu_env *env,
1380                                     struct dt_object *dt)
1381 {
1382         struct osd_object *obj = osd_dt_obj(dt);
1383         struct osd_thread_info *oti = osd_oti_get(env);
1384
1385         LINVRNT(osd_invariant(obj));
1386
1387         LASSERT(obj->oo_owner == env);
1388         LASSERT(oti->oti_w_locks > 0);
1389         oti->oti_w_locks--;
1390         obj->oo_owner = NULL;
1391         up_write(&obj->oo_sem);
1392 }
1393
1394 static int osd_object_write_locked(const struct lu_env *env,
1395                                    struct dt_object *dt)
1396 {
1397         struct osd_object *obj = osd_dt_obj(dt);
1398
1399         LINVRNT(osd_invariant(obj));
1400
1401         return obj->oo_owner == env;
1402 }
1403
1404 static int capa_is_sane(const struct lu_env *env,
1405                         struct osd_device *dev,
1406                         struct lustre_capa *capa,
1407                         struct lustre_capa_key *keys)
1408 {
1409         struct osd_thread_info *oti = osd_oti_get(env);
1410         struct lustre_capa *tcapa = &oti->oti_capa;
1411         struct obd_capa *oc;
1412         int i, rc = 0;
1413         ENTRY;
1414
1415         oc = capa_lookup(dev->od_capa_hash, capa, 0);
1416         if (oc) {
1417                 if (capa_is_expired(oc)) {
1418                         DEBUG_CAPA(D_ERROR, capa, "expired");
1419                         rc = -ESTALE;
1420                 }
1421                 capa_put(oc);
1422                 RETURN(rc);
1423         }
1424
1425         if (capa_is_expired_sec(capa)) {
1426                 DEBUG_CAPA(D_ERROR, capa, "expired");
1427                 RETURN(-ESTALE);
1428         }
1429
1430         spin_lock(&capa_lock);
1431         for (i = 0; i < 2; i++) {
1432                 if (keys[i].lk_keyid == capa->lc_keyid) {
1433                         oti->oti_capa_key = keys[i];
1434                         break;
1435                 }
1436         }
1437         spin_unlock(&capa_lock);
1438
1439         if (i == 2) {
1440                 DEBUG_CAPA(D_ERROR, capa, "no matched capa key");
1441                 RETURN(-ESTALE);
1442         }
1443
1444         rc = capa_hmac(tcapa->lc_hmac, capa, oti->oti_capa_key.lk_key);
1445         if (rc)
1446                 RETURN(rc);
1447
1448         if (memcmp(tcapa->lc_hmac, capa->lc_hmac, sizeof(capa->lc_hmac))) {
1449                 DEBUG_CAPA(D_ERROR, capa, "HMAC mismatch");
1450                 RETURN(-EACCES);
1451         }
1452
1453         oc = capa_add(dev->od_capa_hash, capa);
1454         capa_put(oc);
1455
1456         RETURN(0);
1457 }
1458
1459 int osd_object_auth(const struct lu_env *env, struct dt_object *dt,
1460                     struct lustre_capa *capa, __u64 opc)
1461 {
1462         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
1463         struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
1464         struct lu_capainfo *lci;
1465         int rc;
1466
1467         if (!osd->od_fl_capa)
1468                 return 0;
1469
1470         if (capa == BYPASS_CAPA)
1471                 return 0;
1472
1473         lci = lu_capainfo_get(env);
1474         if (unlikely(lci == NULL))
1475                 return 0;
1476
1477         if (lci->lci_auth == LC_ID_NONE)
1478                 return 0;
1479
1480         if (capa == NULL) {
1481                 CERROR("%s: no capability provided for FID "DFID": rc = %d\n",
1482                        osd_name(osd), PFID(fid), -EACCES);
1483                 return -EACCES;
1484         }
1485
1486         if (!lu_fid_eq(fid, &capa->lc_fid)) {
1487                 DEBUG_CAPA(D_ERROR, capa, "fid "DFID" mismatch with",
1488                            PFID(fid));
1489                 return -EACCES;
1490         }
1491
1492         if (!capa_opc_supported(capa, opc)) {
1493                 DEBUG_CAPA(D_ERROR, capa, "opc "LPX64" not supported by", opc);
1494                 return -EACCES;
1495         }
1496
1497         rc = capa_is_sane(env, osd, capa, osd->od_capa_keys);
1498         if (rc != 0) {
1499                 DEBUG_CAPA(D_ERROR, capa, "insane: rc = %d", rc);
1500                 return -EACCES;
1501         }
1502
1503         return 0;
1504 }
1505
1506 static struct timespec *osd_inode_time(const struct lu_env *env,
1507                                        struct inode *inode, __u64 seconds)
1508 {
1509         struct osd_thread_info  *oti = osd_oti_get(env);
1510         struct timespec         *t   = &oti->oti_time;
1511
1512         t->tv_sec = seconds;
1513         t->tv_nsec = 0;
1514         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
1515         return t;
1516 }
1517
1518
1519 static void osd_inode_getattr(const struct lu_env *env,
1520                               struct inode *inode, struct lu_attr *attr)
1521 {
1522         attr->la_valid      |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
1523                                LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
1524                                LA_FLAGS | LA_NLINK | LA_RDEV | LA_BLKSIZE |
1525                                LA_TYPE;
1526
1527         attr->la_atime      = LTIME_S(inode->i_atime);
1528         attr->la_mtime      = LTIME_S(inode->i_mtime);
1529         attr->la_ctime      = LTIME_S(inode->i_ctime);
1530         attr->la_mode       = inode->i_mode;
1531         attr->la_size       = i_size_read(inode);
1532         attr->la_blocks     = inode->i_blocks;
1533         attr->la_uid        = inode->i_uid;
1534         attr->la_gid        = inode->i_gid;
1535         attr->la_flags      = LDISKFS_I(inode)->i_flags;
1536         attr->la_nlink      = inode->i_nlink;
1537         attr->la_rdev       = inode->i_rdev;
1538         attr->la_blksize    = 1 << inode->i_blkbits;
1539         attr->la_blkbits    = inode->i_blkbits;
1540 }
1541
1542 static int osd_attr_get(const struct lu_env *env,
1543                         struct dt_object *dt,
1544                         struct lu_attr *attr,
1545                         struct lustre_capa *capa)
1546 {
1547         struct osd_object *obj = osd_dt_obj(dt);
1548
1549         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1550         LINVRNT(osd_invariant(obj));
1551
1552         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
1553                 return -EACCES;
1554
1555         spin_lock(&obj->oo_guard);
1556         osd_inode_getattr(env, obj->oo_inode, attr);
1557         spin_unlock(&obj->oo_guard);
1558         return 0;
1559 }
1560
1561 static int osd_declare_attr_set(const struct lu_env *env,
1562                                 struct dt_object *dt,
1563                                 const struct lu_attr *attr,
1564                                 struct thandle *handle)
1565 {
1566         struct osd_thandle     *oh;
1567         struct osd_object      *obj;
1568         struct osd_thread_info *info = osd_oti_get(env);
1569         struct lquota_id_info  *qi = &info->oti_qi;
1570         long long               bspace;
1571         int                     rc = 0;
1572         bool                    allocated;
1573         ENTRY;
1574
1575         LASSERT(dt != NULL);
1576         LASSERT(handle != NULL);
1577
1578         obj = osd_dt_obj(dt);
1579         LASSERT(osd_invariant(obj));
1580
1581         oh = container_of0(handle, struct osd_thandle, ot_super);
1582         LASSERT(oh->ot_handle == NULL);
1583
1584         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
1585                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
1586
1587         if (attr == NULL || obj->oo_inode == NULL)
1588                 RETURN(rc);
1589
1590         bspace   = obj->oo_inode->i_blocks;
1591         bspace <<= obj->oo_inode->i_sb->s_blocksize_bits;
1592         bspace   = toqb(bspace);
1593
1594         /* Changing ownership is always preformed by super user, it should not
1595          * fail with EDQUOT.
1596          *
1597          * We still need to call the osd_declare_qid() to calculate the journal
1598          * credits for updating quota accounting files and to trigger quota
1599          * space adjustment once the operation is completed.*/
1600         if ((attr->la_valid & LA_UID) != 0 &&
1601              attr->la_uid != obj->oo_inode->i_uid) {
1602                 qi->lqi_type = USRQUOTA;
1603
1604                 /* inode accounting */
1605                 qi->lqi_is_blk = false;
1606
1607                 /* one more inode for the new owner ... */
1608                 qi->lqi_id.qid_uid = attr->la_uid;
1609                 qi->lqi_space      = 1;
1610                 allocated = (attr->la_uid == 0) ? true : false;
1611                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1612                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1613                         rc = 0;
1614                 if (rc)
1615                         RETURN(rc);
1616
1617                 /* and one less inode for the current uid */
1618                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1619                 qi->lqi_space      = -1;
1620                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1621                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1622                         rc = 0;
1623                 if (rc)
1624                         RETURN(rc);
1625
1626                 /* block accounting */
1627                 qi->lqi_is_blk = true;
1628
1629                 /* more blocks for the new owner ... */
1630                 qi->lqi_id.qid_uid = attr->la_uid;
1631                 qi->lqi_space      = bspace;
1632                 allocated = (attr->la_uid == 0) ? true : false;
1633                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1634                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1635                         rc = 0;
1636                 if (rc)
1637                         RETURN(rc);
1638
1639                 /* and finally less blocks for the current owner */
1640                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1641                 qi->lqi_space      = -bspace;
1642                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1643                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1644                         rc = 0;
1645                 if (rc)
1646                         RETURN(rc);
1647         }
1648
1649         if (attr->la_valid & LA_GID &&
1650             attr->la_gid != obj->oo_inode->i_gid) {
1651                 qi->lqi_type = GRPQUOTA;
1652
1653                 /* inode accounting */
1654                 qi->lqi_is_blk = false;
1655
1656                 /* one more inode for the new group owner ... */
1657                 qi->lqi_id.qid_gid = attr->la_gid;
1658                 qi->lqi_space      = 1;
1659                 allocated = (attr->la_gid == 0) ? true : false;
1660                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1661                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1662                         rc = 0;
1663                 if (rc)
1664                         RETURN(rc);
1665
1666                 /* and one less inode for the current gid */
1667                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1668                 qi->lqi_space      = -1;
1669                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1670                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1671                         rc = 0;
1672                 if (rc)
1673                         RETURN(rc);
1674
1675                 /* block accounting */
1676                 qi->lqi_is_blk = true;
1677
1678                 /* more blocks for the new owner ... */
1679                 qi->lqi_id.qid_gid = attr->la_gid;
1680                 qi->lqi_space      = bspace;
1681                 allocated = (attr->la_gid == 0) ? true : false;
1682                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1683                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1684                         rc = 0;
1685                 if (rc)
1686                         RETURN(rc);
1687
1688                 /* and finally less blocks for the current owner */
1689                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1690                 qi->lqi_space      = -bspace;
1691                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1692                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1693                         rc = 0;
1694                 if (rc)
1695                         RETURN(rc);
1696         }
1697
1698         RETURN(rc);
1699 }
1700
1701 static int osd_inode_setattr(const struct lu_env *env,
1702                              struct inode *inode, const struct lu_attr *attr)
1703 {
1704         __u64 bits;
1705
1706         bits = attr->la_valid;
1707
1708         if (bits & LA_ATIME)
1709                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
1710         if (bits & LA_CTIME)
1711                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
1712         if (bits & LA_MTIME)
1713                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
1714         if (bits & LA_SIZE) {
1715                 LDISKFS_I(inode)->i_disksize = attr->la_size;
1716                 i_size_write(inode, attr->la_size);
1717         }
1718
1719 #if 0
1720         /* OSD should not change "i_blocks" which is used by quota.
1721          * "i_blocks" should be changed by ldiskfs only. */
1722         if (bits & LA_BLOCKS)
1723                 inode->i_blocks = attr->la_blocks;
1724 #endif
1725         if (bits & LA_MODE)
1726                 inode->i_mode   = (inode->i_mode & S_IFMT) |
1727                         (attr->la_mode & ~S_IFMT);
1728         if (bits & LA_UID)
1729                 inode->i_uid    = attr->la_uid;
1730         if (bits & LA_GID)
1731                 inode->i_gid    = attr->la_gid;
1732         if (bits & LA_NLINK)
1733                 set_nlink(inode, attr->la_nlink);
1734         if (bits & LA_RDEV)
1735                 inode->i_rdev   = attr->la_rdev;
1736
1737         if (bits & LA_FLAGS) {
1738                 /* always keep S_NOCMTIME */
1739                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
1740                                  S_NOCMTIME;
1741         }
1742         return 0;
1743 }
1744
1745 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
1746 {
1747         if ((attr->la_valid & LA_UID && attr->la_uid != inode->i_uid) ||
1748             (attr->la_valid & LA_GID && attr->la_gid != inode->i_gid)) {
1749                 struct iattr    iattr;
1750                 int             rc;
1751
1752                 iattr.ia_valid = 0;
1753                 if (attr->la_valid & LA_UID)
1754                         iattr.ia_valid |= ATTR_UID;
1755                 if (attr->la_valid & LA_GID)
1756                         iattr.ia_valid |= ATTR_GID;
1757                 iattr.ia_uid = attr->la_uid;
1758                 iattr.ia_gid = attr->la_gid;
1759
1760                 rc = ll_vfs_dq_transfer(inode, &iattr);
1761                 if (rc) {
1762                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
1763                                "enforcement enabled on the ldiskfs filesystem?",
1764                                inode->i_sb->s_id, rc);
1765                         return rc;
1766                 }
1767         }
1768         return 0;
1769 }
1770
1771 static int osd_attr_set(const struct lu_env *env,
1772                         struct dt_object *dt,
1773                         const struct lu_attr *attr,
1774                         struct thandle *handle,
1775                         struct lustre_capa *capa)
1776 {
1777         struct osd_object *obj = osd_dt_obj(dt);
1778         struct inode      *inode;
1779         int rc;
1780
1781         LASSERT(handle != NULL);
1782         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1783         LASSERT(osd_invariant(obj));
1784
1785         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
1786                 return -EACCES;
1787
1788         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
1789
1790         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING)) {
1791                 struct osd_thread_info  *oti  = osd_oti_get(env);
1792                 const struct lu_fid     *fid0 = lu_object_fid(&dt->do_lu);
1793                 struct lu_fid           *fid1 = &oti->oti_fid;
1794                 struct osd_inode_id     *id   = &oti->oti_id;
1795                 struct iam_path_descr   *ipd;
1796                 struct iam_container    *bag;
1797                 struct osd_thandle      *oh;
1798                 int                      rc;
1799
1800                 fid_cpu_to_be(fid1, fid0);
1801                 memset(id, 1, sizeof(*id));
1802                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
1803                                   fid0)->oi_dir.od_container;
1804                 ipd = osd_idx_ipd_get(env, bag);
1805                 if (unlikely(ipd == NULL))
1806                         RETURN(-ENOMEM);
1807
1808                 oh = container_of0(handle, struct osd_thandle, ot_super);
1809                 rc = iam_update(oh->ot_handle, bag, (const struct iam_key *)fid1,
1810                                 (const struct iam_rec *)id, ipd);
1811                 osd_ipd_put(env, bag, ipd);
1812                 return(rc > 0 ? 0 : rc);
1813         }
1814
1815         inode = obj->oo_inode;
1816         ll_vfs_dq_init(inode);
1817
1818         rc = osd_quota_transfer(inode, attr);
1819         if (rc)
1820                 return rc;
1821
1822         spin_lock(&obj->oo_guard);
1823         rc = osd_inode_setattr(env, inode, attr);
1824         spin_unlock(&obj->oo_guard);
1825
1826         if (!rc)
1827                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
1828         return rc;
1829 }
1830
1831 struct dentry *osd_child_dentry_get(const struct lu_env *env,
1832                                     struct osd_object *obj,
1833                                     const char *name, const int namelen)
1834 {
1835         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
1836 }
1837
1838 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
1839                       umode_t mode, struct dt_allocation_hint *hint,
1840                       struct thandle *th)
1841 {
1842         int result;
1843         struct osd_device  *osd = osd_obj2dev(obj);
1844         struct osd_thandle *oth;
1845         struct dt_object   *parent = NULL;
1846         struct inode       *inode;
1847
1848         LINVRNT(osd_invariant(obj));
1849         LASSERT(obj->oo_inode == NULL);
1850         LASSERT(obj->oo_hl_head == NULL);
1851
1852         if (S_ISDIR(mode) && ldiskfs_pdo) {
1853                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1854                 if (obj->oo_hl_head == NULL)
1855                         return -ENOMEM;
1856         }
1857
1858         oth = container_of(th, struct osd_thandle, ot_super);
1859         LASSERT(oth->ot_handle->h_transaction != NULL);
1860
1861         if (hint && hint->dah_parent)
1862                 parent = hint->dah_parent;
1863
1864         inode = ldiskfs_create_inode(oth->ot_handle,
1865                                      parent ? osd_dt_obj(parent)->oo_inode :
1866                                               osd_sb(osd)->s_root->d_inode,
1867                                      mode);
1868         if (!IS_ERR(inode)) {
1869                 /* Do not update file c/mtime in ldiskfs.
1870                  * NB: don't need any lock because no contention at this
1871                  * early stage */
1872                 inode->i_flags |= S_NOCMTIME;
1873
1874                 /* For new created object, it must be consistent,
1875                  * and it is unnecessary to scrub against it. */
1876                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
1877                 obj->oo_inode = inode;
1878                 result = 0;
1879         } else {
1880                 if (obj->oo_hl_head != NULL) {
1881                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1882                         obj->oo_hl_head = NULL;
1883                 }
1884                 result = PTR_ERR(inode);
1885         }
1886         LINVRNT(osd_invariant(obj));
1887         return result;
1888 }
1889
1890 enum {
1891         OSD_NAME_LEN = 255
1892 };
1893
1894 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
1895                      struct lu_attr *attr,
1896                      struct dt_allocation_hint *hint,
1897                      struct dt_object_format *dof,
1898                      struct thandle *th)
1899 {
1900         int result;
1901         struct osd_thandle *oth;
1902         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX));
1903
1904         LASSERT(S_ISDIR(attr->la_mode));
1905
1906         oth = container_of(th, struct osd_thandle, ot_super);
1907         LASSERT(oth->ot_handle->h_transaction != NULL);
1908         result = osd_mkfile(info, obj, mode, hint, th);
1909
1910         return result;
1911 }
1912
1913 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
1914                         struct lu_attr *attr,
1915                         struct dt_allocation_hint *hint,
1916                         struct dt_object_format *dof,
1917                         struct thandle *th)
1918 {
1919         int result;
1920         struct osd_thandle *oth;
1921         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
1922
1923         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
1924
1925         LASSERT(S_ISREG(attr->la_mode));
1926
1927         oth = container_of(th, struct osd_thandle, ot_super);
1928         LASSERT(oth->ot_handle->h_transaction != NULL);
1929
1930         result = osd_mkfile(info, obj, mode, hint, th);
1931         if (result == 0) {
1932                 LASSERT(obj->oo_inode != NULL);
1933                 if (feat->dif_flags & DT_IND_VARKEY)
1934                         result = iam_lvar_create(obj->oo_inode,
1935                                                  feat->dif_keysize_max,
1936                                                  feat->dif_ptrsize,
1937                                                  feat->dif_recsize_max,
1938                                                  oth->ot_handle);
1939                 else
1940                         result = iam_lfix_create(obj->oo_inode,
1941                                                  feat->dif_keysize_max,
1942                                                  feat->dif_ptrsize,
1943                                                  feat->dif_recsize_max,
1944                                                  oth->ot_handle);
1945
1946         }
1947         return result;
1948 }
1949
1950 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
1951                      struct lu_attr *attr,
1952                      struct dt_allocation_hint *hint,
1953                      struct dt_object_format *dof,
1954                      struct thandle *th)
1955 {
1956         LASSERT(S_ISREG(attr->la_mode));
1957         return osd_mkfile(info, obj, (attr->la_mode &
1958                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
1959 }
1960
1961 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
1962                      struct lu_attr *attr,
1963                      struct dt_allocation_hint *hint,
1964                      struct dt_object_format *dof,
1965                      struct thandle *th)
1966 {
1967         LASSERT(S_ISLNK(attr->la_mode));
1968         return osd_mkfile(info, obj, (attr->la_mode &
1969                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
1970 }
1971
1972 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
1973                      struct lu_attr *attr,
1974                      struct dt_allocation_hint *hint,
1975                      struct dt_object_format *dof,
1976                      struct thandle *th)
1977 {
1978         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
1979         int result;
1980
1981         LINVRNT(osd_invariant(obj));
1982         LASSERT(obj->oo_inode == NULL);
1983         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
1984                 S_ISFIFO(mode) || S_ISSOCK(mode));
1985
1986         result = osd_mkfile(info, obj, mode, hint, th);
1987         if (result == 0) {
1988                 LASSERT(obj->oo_inode != NULL);
1989                 /*
1990                  * This inode should be marked dirty for i_rdev.  Currently
1991                  * that is done in the osd_attr_init().
1992                  */
1993                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
1994                                    attr->la_rdev);
1995         }
1996         LINVRNT(osd_invariant(obj));
1997         return result;
1998 }
1999
2000 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
2001                               struct lu_attr *,
2002                               struct dt_allocation_hint *hint,
2003                               struct dt_object_format *dof,
2004                               struct thandle *);
2005
2006 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
2007 {
2008         osd_obj_type_f result;
2009
2010         switch (type) {
2011         case DFT_DIR:
2012                 result = osd_mkdir;
2013                 break;
2014         case DFT_REGULAR:
2015                 result = osd_mkreg;
2016                 break;
2017         case DFT_SYM:
2018                 result = osd_mksym;
2019                 break;
2020         case DFT_NODE:
2021                 result = osd_mknod;
2022                 break;
2023         case DFT_INDEX:
2024                 result = osd_mk_index;
2025                 break;
2026
2027         default:
2028                 LBUG();
2029                 break;
2030         }
2031         return result;
2032 }
2033
2034
2035 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
2036                         struct dt_object *parent, struct dt_object *child,
2037                         umode_t child_mode)
2038 {
2039         LASSERT(ah);
2040
2041         memset(ah, 0, sizeof(*ah));
2042         ah->dah_parent = parent;
2043         ah->dah_mode = child_mode;
2044 }
2045
2046 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
2047                           struct lu_attr *attr, struct dt_object_format *dof)
2048 {
2049         struct inode   *inode = obj->oo_inode;
2050         __u64           valid = attr->la_valid;
2051         int             result;
2052
2053         attr->la_valid &= ~(LA_TYPE | LA_MODE);
2054
2055         if (dof->dof_type != DFT_NODE)
2056                 attr->la_valid &= ~LA_RDEV;
2057         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
2058                 attr->la_valid &= ~LA_ATIME;
2059         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
2060                 attr->la_valid &= ~LA_CTIME;
2061         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
2062                 attr->la_valid &= ~LA_MTIME;
2063
2064         result = osd_quota_transfer(inode, attr);
2065         if (result)
2066                 return;
2067
2068         if (attr->la_valid != 0) {
2069                 result = osd_inode_setattr(info->oti_env, inode, attr);
2070                 /*
2071                  * The osd_inode_setattr() should always succeed here.  The
2072                  * only error that could be returned is EDQUOT when we are
2073                  * trying to change the UID or GID of the inode. However, this
2074                  * should not happen since quota enforcement is no longer
2075                  * enabled on ldiskfs (lquota takes care of it).
2076                  */
2077                 LASSERTF(result == 0, "%d", result);
2078                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2079         }
2080
2081         attr->la_valid = valid;
2082 }
2083
2084 /**
2085  * Helper function for osd_object_create()
2086  *
2087  * \retval 0, on success
2088  */
2089 static int __osd_object_create(struct osd_thread_info *info,
2090                                struct osd_object *obj, struct lu_attr *attr,
2091                                struct dt_allocation_hint *hint,
2092                                struct dt_object_format *dof,
2093                                struct thandle *th)
2094 {
2095         int     result;
2096         __u32   umask;
2097
2098         /* we drop umask so that permissions we pass are not affected */
2099         umask = current->fs->umask;
2100         current->fs->umask = 0;
2101
2102         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
2103                                                   th);
2104         if (result == 0) {
2105                 osd_attr_init(info, obj, attr, dof);
2106                 osd_object_init0(obj);
2107                 /* bz 24037 */
2108                 if (obj->oo_inode && (obj->oo_inode->i_state & I_NEW))
2109                         unlock_new_inode(obj->oo_inode);
2110         }
2111
2112         /* restore previous umask value */
2113         current->fs->umask = umask;
2114
2115         return result;
2116 }
2117
2118 /**
2119  * Helper function for osd_object_create()
2120  *
2121  * \retval 0, on success
2122  */
2123 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
2124                            const struct lu_fid *fid, struct thandle *th)
2125 {
2126         struct osd_thread_info *info = osd_oti_get(env);
2127         struct osd_inode_id    *id   = &info->oti_id;
2128         struct osd_device      *osd  = osd_obj2dev(obj);
2129
2130         LASSERT(obj->oo_inode != NULL);
2131
2132         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
2133         return osd_oi_insert(info, osd, fid, id, th, OI_CHECK_FLD);
2134 }
2135
2136 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
2137                    obd_seq seq, struct lu_seq_range *range)
2138 {
2139         struct seq_server_site  *ss = osd_seq_site(osd);
2140         int                     rc;
2141
2142         if (fid_seq_is_idif(seq)) {
2143                 fld_range_set_ost(range);
2144                 range->lsr_index = idif_ost_idx(seq);
2145                 return 0;
2146         }
2147
2148         if (!fid_seq_in_fldb(seq)) {
2149                 fld_range_set_mdt(range);
2150                 if (ss != NULL)
2151                         /* FIXME: If ss is NULL, it suppose not get lsr_index
2152                          * at all */
2153                         range->lsr_index = ss->ss_node_id;
2154                 return 0;
2155         }
2156
2157         LASSERT(ss != NULL);
2158         fld_range_set_any(range);
2159         rc = fld_server_lookup(env, ss->ss_server_fld, seq, range);
2160         if (rc != 0) {
2161                 CERROR("%s: cannot find FLD range for "LPX64": rc = %d\n",
2162                        osd_name(osd), seq, rc);
2163         }
2164         return rc;
2165 }
2166
2167 /*
2168  * Concurrency: no external locking is necessary.
2169  */
2170 static int osd_declare_object_create(const struct lu_env *env,
2171                                      struct dt_object *dt,
2172                                      struct lu_attr *attr,
2173                                      struct dt_allocation_hint *hint,
2174                                      struct dt_object_format *dof,
2175                                      struct thandle *handle)
2176 {
2177         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
2178         struct osd_thandle      *oh;
2179         int                      rc;
2180         ENTRY;
2181
2182         LASSERT(handle != NULL);
2183
2184         oh = container_of0(handle, struct osd_thandle, ot_super);
2185         LASSERT(oh->ot_handle == NULL);
2186
2187         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
2188                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
2189         if (!fid_is_on_ost(osd_oti_get(env), osd_dt_dev(handle->th_dev),
2190                            lu_object_fid(&dt->do_lu), OI_CHECK_FLD))
2191                 /* Reuse idle OI block may cause additional one OI block
2192                  * to be changed. */
2193                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2194                                 osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
2195
2196         /* If this is directory, then we expect . and .. to be inserted as
2197          * well. The one directory block always needs to be created for the
2198          * directory, so we could use DTO_WRITE_BASE here (GDT, block bitmap,
2199          * block), there is no danger of needing a tree for the first block.
2200          */
2201         if (attr && S_ISDIR(attr->la_mode)) {
2202                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2203                                      osd_dto_credits_noquota[DTO_WRITE_BASE]);
2204                 osd_trans_declare_op(env, oh, OSD_OT_INSERT, 0);
2205         }
2206
2207         if (!attr)
2208                 RETURN(0);
2209
2210         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid, 1, oh,
2211                                    false, false, NULL, false);
2212         if (rc != 0)
2213                 RETURN(rc);
2214
2215         /* It does fld look up inside declare, and the result will be
2216          * added to fld cache, so the following fld lookup inside insert
2217          * does not need send RPC anymore, so avoid send rpc with holding
2218          * transaction */
2219         if (fid_is_norm(lu_object_fid(&dt->do_lu)) &&
2220                 !fid_is_last_id(lu_object_fid(&dt->do_lu)))
2221                 osd_fld_lookup(env, osd_dt_dev(handle->th_dev),
2222                                fid_seq(lu_object_fid(&dt->do_lu)), range);
2223
2224
2225         RETURN(rc);
2226 }
2227
2228 static int osd_object_create(const struct lu_env *env, struct dt_object *dt,
2229                              struct lu_attr *attr,
2230                              struct dt_allocation_hint *hint,
2231                              struct dt_object_format *dof,
2232                              struct thandle *th)
2233 {
2234         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2235         struct osd_object      *obj    = osd_dt_obj(dt);
2236         struct osd_thread_info *info   = osd_oti_get(env);
2237         int result;
2238
2239         ENTRY;
2240
2241         LINVRNT(osd_invariant(obj));
2242         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2243         LASSERT(osd_write_locked(env, obj));
2244         LASSERT(th != NULL);
2245
2246         if (unlikely(fid_is_acct(fid)))
2247                 /* Quota files can't be created from the kernel any more,
2248                  * 'tune2fs -O quota' will take care of creating them */
2249                 RETURN(-EPERM);
2250
2251         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2252         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2253
2254         result = __osd_object_create(info, obj, attr, hint, dof, th);
2255         if (result == 0)
2256                 result = __osd_oi_insert(env, obj, fid, th);
2257
2258         LASSERT(ergo(result == 0,
2259                      dt_object_exists(dt) && !dt_object_remote(dt)));
2260
2261         LASSERT(osd_invariant(obj));
2262         RETURN(result);
2263 }
2264
2265 /**
2266  * Called to destroy on-disk representation of the object
2267  *
2268  * Concurrency: must be locked
2269  */
2270 static int osd_declare_object_destroy(const struct lu_env *env,
2271                                       struct dt_object *dt,
2272                                       struct thandle *th)
2273 {
2274         struct osd_object  *obj = osd_dt_obj(dt);
2275         struct inode       *inode = obj->oo_inode;
2276         struct osd_thandle *oh;
2277         int                 rc;
2278         ENTRY;
2279
2280         oh = container_of0(th, struct osd_thandle, ot_super);
2281         LASSERT(oh->ot_handle == NULL);
2282         LASSERT(inode);
2283
2284         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
2285                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
2286         /* Recycle idle OI leaf may cause additional three OI blocks
2287          * to be changed. */
2288         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
2289                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
2290         /* one less inode */
2291         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, -1, oh,
2292                                    false, true, NULL, false);
2293         if (rc)
2294                 RETURN(rc);
2295         /* data to be truncated */
2296         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
2297                                    true, true, NULL, false);
2298         RETURN(rc);
2299 }
2300
2301 static int osd_object_destroy(const struct lu_env *env,
2302                               struct dt_object *dt,
2303                               struct thandle *th)
2304 {
2305         const struct lu_fid    *fid = lu_object_fid(&dt->do_lu);
2306         struct osd_object      *obj = osd_dt_obj(dt);
2307         struct inode           *inode = obj->oo_inode;
2308         struct osd_device      *osd = osd_obj2dev(obj);
2309         struct osd_thandle     *oh;
2310         int                     result;
2311         ENTRY;
2312
2313         oh = container_of0(th, struct osd_thandle, ot_super);
2314         LASSERT(oh->ot_handle);
2315         LASSERT(inode);
2316         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
2317
2318         if (unlikely(fid_is_acct(fid)))
2319                 RETURN(-EPERM);
2320
2321         if (S_ISDIR(inode->i_mode)) {
2322                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1 ||
2323                         inode->i_nlink == 2);
2324                 /* it will check/delete the inode from remote parent,
2325                  * how to optimize it? unlink performance impaction XXX */
2326                 result = osd_delete_from_remote_parent(env, osd, obj, oh);
2327                 if (result != 0 && result != -ENOENT) {
2328                         CERROR("%s: delete inode "DFID": rc = %d\n",
2329                                osd_name(osd), PFID(fid), result);
2330                 }
2331                 spin_lock(&obj->oo_guard);
2332                 clear_nlink(inode);
2333                 spin_unlock(&obj->oo_guard);
2334                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2335         }
2336
2337         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
2338
2339         result = osd_oi_delete(osd_oti_get(env), osd, fid, th, OI_CHECK_FLD);
2340
2341         /* XXX: add to ext3 orphan list */
2342         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
2343
2344         /* not needed in the cache anymore */
2345         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
2346
2347         RETURN(0);
2348 }
2349
2350 /**
2351  * Put the fid into lustre_mdt_attrs, and then place the structure
2352  * inode's ea. This fid should not be altered during the life time
2353  * of the inode.
2354  *
2355  * \retval +ve, on success
2356  * \retval -ve, on error
2357  *
2358  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
2359  */
2360 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
2361                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
2362 {
2363         struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
2364         int                      rc;
2365         ENTRY;
2366
2367         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
2368                 RETURN(0);
2369
2370         lustre_lma_init(lma, fid, compat, incompat);
2371         lustre_lma_swab(lma);
2372
2373         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma, sizeof(*lma),
2374                              XATTR_CREATE);
2375         /* LMA may already exist, but we need to check that all the
2376          * desired compat/incompat flags have been added. */
2377         if (unlikely(rc == -EEXIST)) {
2378                 if (compat == 0 && incompat == 0)
2379                         RETURN(0);
2380
2381                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
2382                                      XATTR_NAME_LMA, info->oti_mdt_attrs_old,
2383                                      LMA_OLD_SIZE);
2384                 if (rc <= 0)
2385                         RETURN(-EINVAL);
2386
2387                 lustre_lma_swab(lma);
2388                 if (!(~lma->lma_compat & compat) &&
2389                     !(~lma->lma_incompat & incompat))
2390                         RETURN(0);
2391
2392                 lma->lma_compat |= compat;
2393                 lma->lma_incompat |= incompat;
2394                 lustre_lma_swab(lma);
2395                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
2396                                      sizeof(*lma), XATTR_REPLACE);
2397         }
2398
2399         RETURN(rc);
2400 }
2401
2402 /**
2403  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
2404  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
2405  * To have compatilibility with 1.8 ldiskfs driver we need to have
2406  * magic number at start of fid data.
2407  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
2408  * its inmemory API.
2409  */
2410 void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
2411                                   const struct dt_rec *fid)
2412 {
2413         if (!fid_is_namespace_visible((const struct lu_fid *)fid) ||
2414             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
2415                 param->edp_magic = 0;
2416                 return;
2417         }
2418
2419         param->edp_magic = LDISKFS_LUFID_MAGIC;
2420         param->edp_len =  sizeof(struct lu_fid) + 1;
2421         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
2422 }
2423
2424 /**
2425  * Try to read the fid from inode ea into dt_rec.
2426  *
2427  * \param fid object fid.
2428  *
2429  * \retval 0 on success
2430  */
2431 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
2432                           __u32 ino, struct lu_fid *fid,
2433                           struct osd_inode_id *id)
2434 {
2435         struct osd_thread_info *info  = osd_oti_get(env);
2436         struct inode           *inode;
2437         ENTRY;
2438
2439         osd_id_gen(id, ino, OSD_OII_NOGEN);
2440         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
2441         if (IS_ERR(inode))
2442                 RETURN(PTR_ERR(inode));
2443
2444         iput(inode);
2445         RETURN(0);
2446 }
2447
2448 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
2449                                         struct inode *dir,
2450                                         struct inode  *parent_dir,
2451                                         const struct dt_rec *dot_fid,
2452                                         const struct dt_rec *dot_dot_fid,
2453                                         struct osd_thandle *oth)
2454 {
2455         struct ldiskfs_dentry_param *dot_ldp;
2456         struct ldiskfs_dentry_param *dot_dot_ldp;
2457
2458         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
2459         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
2460
2461         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
2462         dot_ldp->edp_magic = 0;
2463         return ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
2464                                         dir, dot_ldp, dot_dot_ldp);
2465 }
2466
2467 /**
2468  * Create an local agent inode for remote entry
2469  */
2470 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
2471                                                   struct osd_device *osd,
2472                                                   struct osd_object *pobj,
2473                                                   const struct lu_fid *fid,
2474                                                   struct thandle *th)
2475 {
2476         struct osd_thread_info  *info = osd_oti_get(env);
2477         struct inode            *local;
2478         struct osd_thandle      *oh;
2479         int                     rc;
2480         ENTRY;
2481
2482         LASSERT(th);
2483         oh = container_of(th, struct osd_thandle, ot_super);
2484         LASSERT(oh->ot_handle->h_transaction != NULL);
2485
2486         /* FIXME: Insert index api needs to know the mode of
2487          * the remote object. Just use S_IFDIR for now */
2488         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, S_IFDIR);
2489         if (IS_ERR(local)) {
2490                 CERROR("%s: create local error %d\n", osd_name(osd),
2491                        (int)PTR_ERR(local));
2492                 RETURN(local);
2493         }
2494
2495         /* Set special LMA flag for local agent inode */
2496         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
2497         if (rc != 0) {
2498                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
2499                        osd_name(osd), PFID(fid), rc);
2500                 RETURN(ERR_PTR(rc));
2501         }
2502
2503         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
2504                 (const struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
2505                 (const struct dt_rec *)fid, oh);
2506         if (rc != 0) {
2507                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
2508                         osd_name(osd), PFID(fid), rc);
2509                 RETURN(ERR_PTR(rc));
2510         }
2511
2512         RETURN(local);
2513 }
2514
2515 /**
2516  * Delete local agent inode for remote entry
2517  */
2518 static int osd_delete_local_agent_inode(const struct lu_env *env,
2519                                         struct osd_device *osd,
2520                                         const struct lu_fid *fid,
2521                                         __u32 ino, struct osd_thandle *oh)
2522 {
2523         struct osd_thread_info  *oti = osd_oti_get(env);
2524         struct osd_inode_id     *id = &oti->oti_id;
2525         struct inode            *inode;
2526         ENTRY;
2527
2528         id->oii_ino = le32_to_cpu(ino);
2529         id->oii_gen = OSD_OII_NOGEN;
2530         inode = osd_iget(oti, osd, id);
2531         if (IS_ERR(inode)) {
2532                 CERROR("%s: iget error "DFID" id %u:%u\n", osd_name(osd),
2533                        PFID(fid), id->oii_ino, id->oii_gen);
2534                 RETURN(PTR_ERR(inode));
2535         }
2536
2537         clear_nlink(inode);
2538         mark_inode_dirty(inode);
2539         CDEBUG(D_INODE, "%s: delete remote inode "DFID" %lu\n",
2540                 osd_name(osd), PFID(fid), inode->i_ino);
2541         iput(inode);
2542         RETURN(0);
2543 }
2544
2545 /**
2546  * OSD layer object create function for interoperability mode (b11826).
2547  * This is mostly similar to osd_object_create(). Only difference being, fid is
2548  * inserted into inode ea here.
2549  *
2550  * \retval   0, on success
2551  * \retval -ve, on error
2552  */
2553 static int osd_object_ea_create(const struct lu_env *env, struct dt_object *dt,
2554                                 struct lu_attr *attr,
2555                                 struct dt_allocation_hint *hint,
2556                                 struct dt_object_format *dof,
2557                                 struct thandle *th)
2558 {
2559         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2560         struct osd_object      *obj    = osd_dt_obj(dt);
2561         struct osd_thread_info *info   = osd_oti_get(env);
2562         int                     result;
2563
2564         ENTRY;
2565
2566         LASSERT(osd_invariant(obj));
2567         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2568         LASSERT(osd_write_locked(env, obj));
2569         LASSERT(th != NULL);
2570
2571         if (unlikely(fid_is_acct(fid)))
2572                 /* Quota files can't be created from the kernel any more,
2573                  * 'tune2fs -O quota' will take care of creating them */
2574                 RETURN(-EPERM);
2575
2576         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2577         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2578
2579         result = __osd_object_create(info, obj, attr, hint, dof, th);
2580         if (result == 0)
2581                 result = osd_ea_fid_set(info, obj->oo_inode, fid,
2582                                 fid_is_on_ost(info, osd_obj2dev(obj),
2583                                               fid, OI_CHECK_FLD) ?
2584                                 LMAC_FID_ON_OST : 0, 0);
2585
2586         if (result == 0)
2587                 result = __osd_oi_insert(env, obj, fid, th);
2588
2589         LASSERT(ergo(result == 0,
2590                      dt_object_exists(dt) && !dt_object_remote(dt)));
2591         LINVRNT(osd_invariant(obj));
2592         RETURN(result);
2593 }
2594
2595 static int osd_declare_object_ref_add(const struct lu_env *env,
2596                                       struct dt_object *dt,
2597                                       struct thandle *handle)
2598 {
2599         struct osd_thandle       *oh;
2600
2601         /* it's possible that object doesn't exist yet */
2602         LASSERT(handle != NULL);
2603
2604         oh = container_of0(handle, struct osd_thandle, ot_super);
2605         LASSERT(oh->ot_handle == NULL);
2606
2607         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
2608                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2609
2610         return 0;
2611 }
2612
2613 /*
2614  * Concurrency: @dt is write locked.
2615  */
2616 static int osd_object_ref_add(const struct lu_env *env,
2617                               struct dt_object *dt, struct thandle *th)
2618 {
2619         struct osd_object  *obj = osd_dt_obj(dt);
2620         struct inode       *inode = obj->oo_inode;
2621         struct osd_thandle *oh;
2622         int                 rc = 0;
2623
2624         LINVRNT(osd_invariant(obj));
2625         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2626         LASSERT(osd_write_locked(env, obj));
2627         LASSERT(th != NULL);
2628
2629         oh = container_of0(th, struct osd_thandle, ot_super);
2630         LASSERT(oh->ot_handle != NULL);
2631
2632         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
2633
2634         /*
2635          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
2636          * (65000) subdirectories by storing "1" in i_nlink if the link count
2637          * would otherwise overflow. Directory tranversal tools understand
2638          * that (st_nlink == 1) indicates that the filesystem dose not track
2639          * hard links count on the directory, and will not abort subdirectory
2640          * scanning early once (st_nlink - 2) subdirs have been found.
2641          *
2642          * This also has to properly handle the case of inodes with nlink == 0
2643          * in case they are being linked into the PENDING directory
2644          */
2645         spin_lock(&obj->oo_guard);
2646         ldiskfs_inc_count(oh->ot_handle, inode);
2647         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
2648         spin_unlock(&obj->oo_guard);
2649
2650         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2651         LINVRNT(osd_invariant(obj));
2652
2653         return rc;
2654 }
2655
2656 static int osd_declare_object_ref_del(const struct lu_env *env,
2657                                       struct dt_object *dt,
2658                                       struct thandle *handle)
2659 {
2660         struct osd_thandle *oh;
2661
2662         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2663         LASSERT(handle != NULL);
2664
2665         oh = container_of0(handle, struct osd_thandle, ot_super);
2666         LASSERT(oh->ot_handle == NULL);
2667
2668         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
2669                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2670
2671         return 0;
2672 }
2673
2674 /*
2675  * Concurrency: @dt is write locked.
2676  */
2677 static int osd_object_ref_del(const struct lu_env *env, struct dt_object *dt,
2678                               struct thandle *th)
2679 {
2680         struct osd_object       *obj = osd_dt_obj(dt);
2681         struct inode            *inode = obj->oo_inode;
2682         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
2683         struct osd_thandle      *oh;
2684
2685         LINVRNT(osd_invariant(obj));
2686         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2687         LASSERT(osd_write_locked(env, obj));
2688         LASSERT(th != NULL);
2689
2690         oh = container_of0(th, struct osd_thandle, ot_super);
2691         LASSERT(oh->ot_handle != NULL);
2692
2693         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
2694
2695         spin_lock(&obj->oo_guard);
2696         /* That can be result of upgrade from old Lustre version and
2697          * applied only to local files.  Just skip this ref_del call.
2698          * ext4_unlink() only treats this as a warning, don't LASSERT here.*/
2699         if (inode->i_nlink == 0) {
2700                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
2701                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
2702                              ", maybe an upgraded file? (LU-3915)\n",
2703                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
2704                 spin_unlock(&obj->oo_guard);
2705                 return 0;
2706         }
2707
2708         ldiskfs_dec_count(oh->ot_handle, inode);
2709         spin_unlock(&obj->oo_guard);
2710
2711         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2712         LINVRNT(osd_invariant(obj));
2713
2714         return 0;
2715 }
2716
2717 /*
2718  * Get the 64-bit version for an inode.
2719  */
2720 static int osd_object_version_get(const struct lu_env *env,
2721                                   struct dt_object *dt, dt_obj_version_t *ver)
2722 {
2723         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2724
2725         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
2726                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2727         *ver = LDISKFS_I(inode)->i_fs_version;
2728         return 0;
2729 }
2730
2731 /*
2732  * Concurrency: @dt is read locked.
2733  */
2734 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
2735                          struct lu_buf *buf, const char *name,
2736                          struct lustre_capa *capa)
2737 {
2738         struct osd_object      *obj    = osd_dt_obj(dt);
2739         struct inode           *inode  = obj->oo_inode;
2740         struct osd_thread_info *info   = osd_oti_get(env);
2741         struct dentry          *dentry = &info->oti_obj_dentry;
2742
2743         /* version get is not real XATTR but uses xattr API */
2744         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2745                 /* for version we are just using xattr API but change inode
2746                  * field instead */
2747                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2748                 osd_object_version_get(env, dt, buf->lb_buf);
2749                 return sizeof(dt_obj_version_t);
2750         }
2751
2752         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2753         LASSERT(inode->i_op != NULL && inode->i_op->getxattr != NULL);
2754
2755         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2756                 return -EACCES;
2757
2758         return __osd_xattr_get(inode, dentry, name, buf->lb_buf, buf->lb_len);
2759 }
2760
2761
2762 static int osd_declare_xattr_set(const struct lu_env *env,
2763                                  struct dt_object *dt,
2764                                  const struct lu_buf *buf, const char *name,
2765                                  int fl, struct thandle *handle)
2766 {
2767         struct osd_thandle *oh;
2768
2769         LASSERT(handle != NULL);
2770
2771         oh = container_of0(handle, struct osd_thandle, ot_super);
2772         LASSERT(oh->ot_handle == NULL);
2773
2774         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2775                              strcmp(name, XATTR_NAME_VERSION) == 0 ?
2776                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] :
2777                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2778
2779         return 0;
2780 }
2781
2782 /*
2783  * Set the 64-bit version for object
2784  */
2785 static void osd_object_version_set(const struct lu_env *env,
2786                                    struct dt_object *dt,
2787                                    dt_obj_version_t *new_version)
2788 {
2789         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2790
2791         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
2792                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2793
2794         LDISKFS_I(inode)->i_fs_version = *new_version;
2795         /** Version is set after all inode operations are finished,
2796          *  so we should mark it dirty here */
2797         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2798 }
2799
2800 /*
2801  * Concurrency: @dt is write locked.
2802  */
2803 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
2804                          const struct lu_buf *buf, const char *name, int fl,
2805                          struct thandle *handle, struct lustre_capa *capa)
2806 {
2807         struct osd_object      *obj      = osd_dt_obj(dt);
2808         struct inode           *inode    = obj->oo_inode;
2809         struct osd_thread_info *info     = osd_oti_get(env);
2810         int                     fs_flags = 0;
2811         ENTRY;
2812
2813         LASSERT(handle != NULL);
2814
2815         /* version set is not real XATTR */
2816         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2817                 /* for version we are just using xattr API but change inode
2818                  * field instead */
2819                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2820                 osd_object_version_set(env, dt, buf->lb_buf);
2821                 return sizeof(dt_obj_version_t);
2822         }
2823
2824         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2825                 return -EACCES;
2826
2827         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2828         if (fl & LU_XATTR_REPLACE)
2829                 fs_flags |= XATTR_REPLACE;
2830
2831         if (fl & LU_XATTR_CREATE)
2832                 fs_flags |= XATTR_CREATE;
2833
2834         return __osd_xattr_set(info, inode, name, buf->lb_buf, buf->lb_len,
2835                                fs_flags);
2836 }
2837
2838 /*
2839  * Concurrency: @dt is read locked.
2840  */
2841 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
2842                           struct lu_buf *buf, struct lustre_capa *capa)
2843 {
2844         struct osd_object      *obj    = osd_dt_obj(dt);
2845         struct inode           *inode  = obj->oo_inode;
2846         struct osd_thread_info *info   = osd_oti_get(env);
2847         struct dentry          *dentry = &info->oti_obj_dentry;
2848
2849         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2850         LASSERT(inode->i_op != NULL && inode->i_op->listxattr != NULL);
2851         LASSERT(osd_read_locked(env, obj) || osd_write_locked(env, obj));
2852
2853         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2854                 return -EACCES;
2855
2856         dentry->d_inode = inode;
2857         dentry->d_sb = inode->i_sb;
2858         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
2859 }
2860
2861 static int osd_declare_xattr_del(const struct lu_env *env,
2862                                  struct dt_object *dt, const char *name,
2863                                  struct thandle *handle)
2864 {
2865         struct osd_thandle *oh;
2866
2867         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2868         LASSERT(handle != NULL);
2869
2870         oh = container_of0(handle, struct osd_thandle, ot_super);
2871         LASSERT(oh->ot_handle == NULL);
2872
2873         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2874                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2875
2876         return 0;
2877 }
2878
2879 /*
2880  * Concurrency: @dt is write locked.
2881  */
2882 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
2883                          const char *name, struct thandle *handle,
2884                          struct lustre_capa *capa)
2885 {
2886         struct osd_object      *obj    = osd_dt_obj(dt);
2887         struct inode           *inode  = obj->oo_inode;
2888         struct osd_thread_info *info   = osd_oti_get(env);
2889         struct dentry          *dentry = &info->oti_obj_dentry;
2890         int                     rc;
2891
2892         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2893         LASSERT(inode->i_op != NULL && inode->i_op->removexattr != NULL);
2894         LASSERT(handle != NULL);
2895
2896         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2897                 return -EACCES;
2898
2899         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2900
2901         ll_vfs_dq_init(inode);
2902         dentry->d_inode = inode;
2903         dentry->d_sb = inode->i_sb;
2904         rc = inode->i_op->removexattr(dentry, name);
2905         return rc;
2906 }
2907
2908 static struct obd_capa *osd_capa_get(const struct lu_env *env,
2909                                      struct dt_object *dt,
2910                                      struct lustre_capa *old, __u64 opc)
2911 {
2912         struct osd_thread_info *info = osd_oti_get(env);
2913         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
2914         struct osd_object *obj = osd_dt_obj(dt);
2915         struct osd_device *osd = osd_obj2dev(obj);
2916         struct lustre_capa_key *key = &info->oti_capa_key;
2917         struct lustre_capa *capa = &info->oti_capa;
2918         struct obd_capa *oc;
2919         struct lu_capainfo *lci;
2920         int rc;
2921         ENTRY;
2922
2923         if (!osd->od_fl_capa)
2924                 RETURN(ERR_PTR(-ENOENT));
2925
2926         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2927         LINVRNT(osd_invariant(obj));
2928
2929         /* renewal sanity check */
2930         if (old && osd_object_auth(env, dt, old, opc))
2931                 RETURN(ERR_PTR(-EACCES));
2932
2933         lci = lu_capainfo_get(env);
2934         if (unlikely(lci == NULL))
2935                 RETURN(ERR_PTR(-ENOENT));
2936
2937         switch (lci->lci_auth) {
2938         case LC_ID_NONE:
2939                 RETURN(NULL);
2940         case LC_ID_PLAIN:
2941                 capa->lc_uid = obj->oo_inode->i_uid;
2942                 capa->lc_gid = obj->oo_inode->i_gid;
2943                 capa->lc_flags = LC_ID_PLAIN;
2944                 break;
2945         case LC_ID_CONVERT: {
2946                 __u32 d[4], s[4];
2947
2948                 s[0] = obj->oo_inode->i_uid;
2949                 cfs_get_random_bytes(&(s[1]), sizeof(__u32));
2950                 s[2] = obj->oo_inode->i_gid;
2951                 cfs_get_random_bytes(&(s[3]), sizeof(__u32));
2952                 rc = capa_encrypt_id(d, s, key->lk_key, CAPA_HMAC_KEY_MAX_LEN);
2953                 if (unlikely(rc))
2954                         RETURN(ERR_PTR(rc));
2955
2956                 capa->lc_uid   = ((__u64)d[1] << 32) | d[0];
2957                 capa->lc_gid   = ((__u64)d[3] << 32) | d[2];
2958                 capa->lc_flags = LC_ID_CONVERT;
2959                 break;
2960         }
2961         default:
2962                 RETURN(ERR_PTR(-EINVAL));
2963         }
2964
2965         capa->lc_fid = *fid;
2966         capa->lc_opc = opc;
2967         capa->lc_flags |= osd->od_capa_alg << 24;
2968         capa->lc_timeout = osd->od_capa_timeout;
2969         capa->lc_expiry = 0;
2970
2971         oc = capa_lookup(osd->od_capa_hash, capa, 1);
2972         if (oc) {
2973                 LASSERT(!capa_is_expired(oc));
2974                 RETURN(oc);
2975         }
2976
2977         spin_lock(&capa_lock);
2978         *key = osd->od_capa_keys[1];
2979         spin_unlock(&capa_lock);
2980
2981         capa->lc_keyid = key->lk_keyid;
2982         capa->lc_expiry = cfs_time_current_sec() + osd->od_capa_timeout;
2983
2984         rc = capa_hmac(capa->lc_hmac, capa, key->lk_key);
2985         if (rc) {
2986                 DEBUG_CAPA(D_ERROR, capa, "HMAC failed: %d for", rc);
2987                 RETURN(ERR_PTR(rc));
2988         }
2989
2990         oc = capa_add(osd->od_capa_hash, capa);
2991         RETURN(oc);
2992 }
2993
2994 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt)
2995 {
2996         struct osd_object       *obj    = osd_dt_obj(dt);
2997         struct inode            *inode  = obj->oo_inode;
2998         struct osd_thread_info  *info   = osd_oti_get(env);
2999         struct dentry           *dentry = &info->oti_obj_dentry;
3000         struct file             *file   = &info->oti_file;
3001         int                     rc;
3002
3003         ENTRY;
3004
3005         dentry->d_inode = inode;
3006         dentry->d_sb = inode->i_sb;
3007         file->f_dentry = dentry;
3008         file->f_mapping = inode->i_mapping;
3009         file->f_op = inode->i_fop;
3010         set_file_inode(file, inode);
3011 #ifndef HAVE_FILE_FSYNC_4ARGS
3012         mutex_lock(&inode->i_mutex);
3013 #endif
3014         rc = do_fsync(file, 0);
3015 #ifndef HAVE_FILE_FSYNC_4ARGS
3016         mutex_unlock(&inode->i_mutex);
3017 #endif
3018         RETURN(rc);
3019 }
3020
3021 static int osd_data_get(const struct lu_env *env, struct dt_object *dt,
3022                         void **data)
3023 {
3024         struct osd_object *obj = osd_dt_obj(dt);
3025         ENTRY;
3026
3027         *data = (void *)obj->oo_inode;
3028         RETURN(0);
3029 }
3030
3031 /*
3032  * Index operations.
3033  */
3034
3035 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
3036                            const struct dt_index_features *feat)
3037 {
3038         struct iam_descr *descr;
3039
3040         if (osd_object_is_root(o))
3041                 return feat == &dt_directory_features;
3042
3043         LASSERT(o->oo_dir != NULL);
3044
3045         descr = o->oo_dir->od_container.ic_descr;
3046         if (feat == &dt_directory_features) {
3047                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
3048                         return 1;
3049                 else
3050                         return 0;
3051         } else {
3052                 return
3053                         feat->dif_keysize_min <= descr->id_key_size &&
3054                         descr->id_key_size <= feat->dif_keysize_max &&
3055                         feat->dif_recsize_min <= descr->id_rec_size &&
3056                         descr->id_rec_size <= feat->dif_recsize_max &&
3057                         !(feat->dif_flags & (DT_IND_VARKEY |
3058                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
3059                         ergo(feat->dif_flags & DT_IND_UPDATE,
3060                              1 /* XXX check that object (and file system) is
3061                                 * writable */);
3062         }
3063 }
3064
3065 static int osd_iam_container_init(const struct lu_env *env,
3066                                   struct osd_object *obj,
3067                                   struct osd_directory *dir)
3068 {
3069         struct iam_container *bag = &dir->od_container;
3070         int result;
3071
3072         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
3073         if (result != 0)
3074                 return result;
3075
3076         result = iam_container_setup(bag);
3077         if (result == 0)
3078                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
3079         else
3080                 iam_container_fini(bag);
3081
3082         return result;
3083 }
3084
3085
3086 /*
3087  * Concurrency: no external locking is necessary.
3088  */
3089 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
3090                          const struct dt_index_features *feat)
3091 {
3092         int                      result;
3093         int                      skip_iam = 0;
3094         struct osd_object       *obj = osd_dt_obj(dt);
3095
3096         LINVRNT(osd_invariant(obj));
3097
3098         if (osd_object_is_root(obj)) {
3099                 dt->do_index_ops = &osd_index_ea_ops;
3100                 result = 0;
3101         } else if (feat == &dt_directory_features) {
3102                 dt->do_index_ops = &osd_index_ea_ops;
3103                 if (obj->oo_inode != NULL && S_ISDIR(obj->oo_inode->i_mode))
3104                         result = 0;
3105                 else
3106                         result = -ENOTDIR;
3107                 skip_iam = 1;
3108         } else if (unlikely(feat == &dt_otable_features)) {
3109                 dt->do_index_ops = &osd_otable_ops;
3110                 return 0;
3111         } else if (unlikely(feat == &dt_acct_features)) {
3112                 dt->do_index_ops = &osd_acct_index_ops;
3113                 result = 0;
3114                 skip_iam = 1;
3115         } else if (!osd_has_index(obj)) {
3116                 struct osd_directory *dir;
3117
3118                 OBD_ALLOC_PTR(dir);
3119                 if (dir != NULL) {
3120
3121                         spin_lock(&obj->oo_guard);
3122                         if (obj->oo_dir == NULL)
3123                                 obj->oo_dir = dir;
3124                         else
3125                                 /*
3126                                  * Concurrent thread allocated container data.
3127                                  */
3128                                 OBD_FREE_PTR(dir);
3129                         spin_unlock(&obj->oo_guard);
3130                         /*
3131                          * Now, that we have container data, serialize its
3132                          * initialization.
3133                          */
3134                         down_write(&obj->oo_ext_idx_sem);
3135                         /*
3136                          * recheck under lock.
3137                          */
3138                         if (!osd_has_index(obj))
3139                                 result = osd_iam_container_init(env, obj, dir);
3140                         else
3141                                 result = 0;
3142                         up_write(&obj->oo_ext_idx_sem);
3143                 } else {
3144                         result = -ENOMEM;
3145                 }
3146         } else {
3147                 result = 0;
3148         }
3149
3150         if (result == 0 && skip_iam == 0) {
3151                 if (!osd_iam_index_probe(env, obj, feat))
3152                         result = -ENOTDIR;
3153         }
3154         LINVRNT(osd_invariant(obj));
3155
3156         if (result == 0 && is_quota_glb_feat(feat) &&
3157             fid_seq(lu_object_fid(&dt->do_lu)) == FID_SEQ_QUOTA_GLB)
3158                 result = osd_quota_migration(env, dt, feat);
3159
3160         return result;
3161 }
3162
3163 static int osd_otable_it_attr_get(const struct lu_env *env,
3164                                  struct dt_object *dt,
3165                                  struct lu_attr *attr,
3166                                  struct lustre_capa *capa)
3167 {
3168         attr->la_valid = 0;
3169         return 0;
3170 }
3171
3172 static const struct dt_object_operations osd_obj_ops = {
3173         .do_read_lock         = osd_object_read_lock,
3174         .do_write_lock        = osd_object_write_lock,
3175         .do_read_unlock       = osd_object_read_unlock,
3176         .do_write_unlock      = osd_object_write_unlock,
3177         .do_write_locked      = osd_object_write_locked,
3178         .do_attr_get          = osd_attr_get,
3179         .do_declare_attr_set  = osd_declare_attr_set,
3180         .do_attr_set          = osd_attr_set,
3181         .do_ah_init           = osd_ah_init,
3182         .do_declare_create    = osd_declare_object_create,
3183         .do_create            = osd_object_create,
3184         .do_declare_destroy   = osd_declare_object_destroy,
3185         .do_destroy           = osd_object_destroy,
3186         .do_index_try         = osd_index_try,
3187         .do_declare_ref_add   = osd_declare_object_ref_add,
3188         .do_ref_add           = osd_object_ref_add,
3189         .do_declare_ref_del   = osd_declare_object_ref_del,
3190         .do_ref_del           = osd_object_ref_del,
3191         .do_xattr_get         = osd_xattr_get,
3192         .do_declare_xattr_set = osd_declare_xattr_set,
3193         .do_xattr_set         = osd_xattr_set,
3194         .do_declare_xattr_del = osd_declare_xattr_del,
3195         .do_xattr_del         = osd_xattr_del,
3196         .do_xattr_list        = osd_xattr_list,
3197         .do_capa_get          = osd_capa_get,
3198         .do_object_sync       = osd_object_sync,
3199         .do_data_get          = osd_data_get,
3200 };
3201
3202 /**
3203  * dt_object_operations for interoperability mode
3204  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
3205  */
3206 static const struct dt_object_operations osd_obj_ea_ops = {
3207         .do_read_lock         = osd_object_read_lock,
3208         .do_write_lock        = osd_object_write_lock,
3209         .do_read_unlock       = osd_object_read_unlock,
3210         .do_write_unlock      = osd_object_write_unlock,
3211         .do_write_locked      = osd_object_write_locked,
3212         .do_attr_get          = osd_attr_get,
3213         .do_declare_attr_set  = osd_declare_attr_set,
3214         .do_attr_set          = osd_attr_set,
3215         .do_ah_init           = osd_ah_init,
3216         .do_declare_create    = osd_declare_object_create,
3217         .do_create            = osd_object_ea_create,
3218         .do_declare_destroy   = osd_declare_object_destroy,
3219         .do_destroy           = osd_object_destroy,
3220         .do_index_try         = osd_index_try,
3221         .do_declare_ref_add   = osd_declare_object_ref_add,
3222         .do_ref_add           = osd_object_ref_add,
3223         .do_declare_ref_del   = osd_declare_object_ref_del,
3224         .do_ref_del           = osd_object_ref_del,
3225         .do_xattr_get         = osd_xattr_get,
3226         .do_declare_xattr_set = osd_declare_xattr_set,
3227         .do_xattr_set         = osd_xattr_set,
3228         .do_declare_xattr_del = osd_declare_xattr_del,
3229         .do_xattr_del         = osd_xattr_del,
3230         .do_xattr_list        = osd_xattr_list,
3231         .do_capa_get          = osd_capa_get,
3232         .do_object_sync       = osd_object_sync,
3233         .do_data_get          = osd_data_get,
3234 };
3235
3236 static const struct dt_object_operations osd_obj_otable_it_ops = {
3237         .do_attr_get    = osd_otable_it_attr_get,
3238         .do_index_try   = osd_index_try,
3239 };
3240
3241 static int osd_index_declare_iam_delete(const struct lu_env *env,
3242                                         struct dt_object *dt,
3243                                         const struct dt_key *key,
3244                                         struct thandle *handle)
3245 {
3246         struct osd_thandle    *oh;
3247
3248         oh = container_of0(handle, struct osd_thandle, ot_super);
3249         LASSERT(oh->ot_handle == NULL);
3250
3251         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3252                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3253
3254         return 0;
3255 }
3256
3257 /**
3258  *      delete a (key, value) pair from index \a dt specified by \a key
3259  *
3260  *      \param  dt      osd index object
3261  *      \param  key     key for index
3262  *      \param  rec     record reference
3263  *      \param  handle  transaction handler
3264  *
3265  *      \retval  0  success
3266  *      \retval -ve   failure
3267  */
3268
3269 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
3270                                 const struct dt_key *key,
3271                                 struct thandle *handle,
3272                                 struct lustre_capa *capa)
3273 {
3274         struct osd_thread_info *oti = osd_oti_get(env);
3275         struct osd_object      *obj = osd_dt_obj(dt);
3276         struct osd_thandle     *oh;
3277         struct iam_path_descr  *ipd;
3278         struct iam_container   *bag = &obj->oo_dir->od_container;
3279         int                     rc;
3280
3281         ENTRY;
3282
3283         LINVRNT(osd_invariant(obj));
3284         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3285         LASSERT(bag->ic_object == obj->oo_inode);
3286         LASSERT(handle != NULL);
3287
3288         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3289                 RETURN(-EACCES);
3290
3291         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3292
3293         ipd = osd_idx_ipd_get(env, bag);
3294         if (unlikely(ipd == NULL))
3295                 RETURN(-ENOMEM);
3296
3297         oh = container_of0(handle, struct osd_thandle, ot_super);
3298         LASSERT(oh->ot_handle != NULL);
3299         LASSERT(oh->ot_handle->h_transaction != NULL);
3300
3301         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3302                 /* swab quota uid/gid provided by caller */
3303                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3304                 key = (const struct dt_key *)&oti->oti_quota_id;
3305         }
3306
3307         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
3308         osd_ipd_put(env, bag, ipd);
3309         LINVRNT(osd_invariant(obj));
3310         RETURN(rc);
3311 }
3312
3313 static int osd_index_declare_ea_delete(const struct lu_env *env,
3314                                        struct dt_object *dt,
3315                                        const struct dt_key *key,
3316                                        struct thandle *handle)
3317 {
3318         struct osd_thandle *oh;
3319         struct inode       *inode;
3320         int                 rc;
3321         ENTRY;
3322
3323         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3324         LASSERT(handle != NULL);
3325
3326         oh = container_of0(handle, struct osd_thandle, ot_super);
3327         LASSERT(oh->ot_handle == NULL);
3328
3329         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3330                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3331
3332         inode = osd_dt_obj(dt)->oo_inode;
3333         LASSERT(inode);
3334
3335         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
3336                                    true, true, NULL, false);
3337         RETURN(rc);
3338 }
3339
3340 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3341                                           struct dt_rec *fid)
3342 {
3343         struct osd_fid_pack *rec;
3344         int                  rc = -ENODATA;
3345
3346         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3347                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3348                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3349         }
3350         return rc;
3351 }
3352
3353 static int osd_mdt_seq_exists(const struct lu_env *env,
3354                               struct osd_device *osd, obd_seq seq)
3355 {
3356         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
3357         struct seq_server_site  *ss = osd_seq_site(osd);
3358         int                     rc;
3359         ENTRY;
3360
3361         if (ss == NULL)
3362                 RETURN(1);
3363
3364         /* XXX: currently, each MDT only store avaible sequence on disk, and no
3365          * allocated sequences information on disk, so we have to lookup FLDB,
3366          * but it probably makes more sense also store allocated sequence
3367          * locally, so we do not need do remote FLDB lookup in OSD */
3368         rc = osd_fld_lookup(env, osd, seq, range);
3369         if (rc != 0) {
3370                 CERROR("%s: Can not lookup fld for "LPX64"\n",
3371                        osd_name(osd), seq);
3372                 RETURN(0);
3373         }
3374
3375         RETURN(ss->ss_node_id == range->lsr_index);
3376 }
3377
3378 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
3379                           struct lu_fid *fid)
3380 {
3381         ENTRY;
3382
3383         /* FID seqs not in FLDB, must be local seq */
3384         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
3385                 RETURN(0);
3386
3387         /* Currently only check this for FID on MDT */
3388         if (osd_mdt_seq_exists(env, osd, fid_seq(fid)))
3389                 RETURN(0);
3390
3391         RETURN(1);
3392 }
3393
3394 /**
3395  * Index delete function for interoperability mode (b11826).
3396  * It will remove the directory entry added by osd_index_ea_insert().
3397  * This entry is needed to maintain name->fid mapping.
3398  *
3399  * \param key,  key i.e. file entry to be deleted
3400  *
3401  * \retval   0, on success
3402  * \retval -ve, on error
3403  */
3404 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3405                                const struct dt_key *key,
3406                                struct thandle *handle,
3407                                struct lustre_capa *capa)
3408 {
3409         struct osd_object          *obj    = osd_dt_obj(dt);
3410         struct inode               *dir    = obj->oo_inode;
3411         struct dentry              *dentry;
3412         struct osd_thandle         *oh;
3413         struct ldiskfs_dir_entry_2 *de = NULL;
3414         struct buffer_head         *bh;
3415         struct htree_lock          *hlock = NULL;
3416         struct lu_fid              *fid = &osd_oti_get(env)->oti_fid;
3417         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
3418         int                        rc;
3419         ENTRY;
3420
3421         LINVRNT(osd_invariant(obj));
3422         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3423         LASSERT(handle != NULL);
3424
3425         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3426
3427         oh = container_of(handle, struct osd_thandle, ot_super);
3428         LASSERT(oh->ot_handle != NULL);
3429         LASSERT(oh->ot_handle->h_transaction != NULL);
3430
3431         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3432                 RETURN(-EACCES);
3433
3434         ll_vfs_dq_init(dir);
3435         dentry = osd_child_dentry_get(env, obj,
3436                                       (char *)key, strlen((char *)key));
3437
3438         if (obj->oo_hl_head != NULL) {
3439                 hlock = osd_oti_get(env)->oti_hlock;
3440                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3441                                    dir, LDISKFS_HLOCK_DEL);
3442         } else {
3443                 down_write(&obj->oo_ext_idx_sem);
3444         }
3445
3446         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
3447         if (bh) {
3448                 __u32 ino = 0;
3449
3450                 /* If this is not the ".." entry, it might be a remote DNE
3451                  * entry and  we need to check if the FID is for a remote
3452                  * MDT.  If the FID is  not in the directory entry (e.g.
3453                  * upgraded 1.8 filesystem without dirdata enabled) then
3454                  * we need to get the FID from the LMA. For a remote directory
3455                  * there HAS to be an LMA, it cannot be an IGIF inode in this
3456                  * case.
3457                  *
3458                  * Delete the entry before the agent inode in order to
3459                  * simplify error handling.  At worst an error after deleting
3460                  * the entry first might leak the agent inode afterward. The
3461                  * reverse would need filesystem abort in case of error deleting
3462                  * the entry after the agent had been removed, or leave a
3463                  * dangling entry pointing at a random inode. */
3464                 if (strcmp((char *)key, dotdot) != 0) {
3465                         LASSERT(de != NULL);
3466                         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
3467                         /* If Fid is not in dentry, try to get it from LMA */
3468                         if (rc == -ENODATA) {
3469                                 struct osd_inode_id *id;
3470                                 struct inode *inode;
3471
3472                                 /* Before trying to get fid from the inode,
3473                                  * check whether the inode is valid.
3474                                  *
3475                                  * If the inode has been deleted, do not go
3476                                  * ahead to do osd_ea_fid_get, which will set
3477                                  * the inode to bad inode, which might cause
3478                                  * the inode to be deleted uncorrectly */
3479                                 inode = ldiskfs_iget(osd_sb(osd),
3480                                                      le32_to_cpu(de->inode));
3481                                 if (IS_ERR(inode)) {
3482                                         CDEBUG(D_INODE, "%s: "DFID"get inode"
3483                                                "error.\n", osd_name(osd),
3484                                                PFID(fid));
3485                                         rc = PTR_ERR(inode);
3486                                 } else {
3487                                         if (likely(inode->i_nlink != 0)) {
3488                                                 id = &osd_oti_get(env)->oti_id;
3489                                                 rc = osd_ea_fid_get(env, obj,
3490                                                         le32_to_cpu(de->inode),
3491                                                                     fid, id);
3492                                         } else {
3493                                                 CDEBUG(D_INFO, "%s: %u "DFID
3494                                                        "deleted.\n",
3495                                                        osd_name(osd),
3496                                                        le32_to_cpu(de->inode),
3497                                                        PFID(fid));
3498                                                 rc = -ESTALE;
3499                                         }
3500                                         iput(inode);
3501                                 }
3502                         }
3503                         if (rc == 0 &&
3504                             unlikely(osd_remote_fid(env, osd, fid)))
3505                                 /* Need to delete agent inode */
3506                                 ino = le32_to_cpu(de->inode);
3507                 }
3508                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
3509                 brelse(bh);
3510                 if (rc == 0 && unlikely(ino != 0)) {
3511                         rc = osd_delete_local_agent_inode(env, osd, fid, ino,
3512                                                           oh);
3513                         if (rc != 0)
3514                                 CERROR("%s: del local inode "DFID": rc = %d\n",
3515                                        osd_name(osd), PFID(fid), rc);
3516                 }
3517         } else {
3518                 rc = -ENOENT;
3519         }
3520         if (hlock != NULL)
3521                 ldiskfs_htree_unlock(hlock);
3522         else
3523                 up_write(&obj->oo_ext_idx_sem);
3524
3525         if (rc != 0)
3526                 GOTO(out, rc);
3527
3528         /* For inode on the remote MDT, .. will point to
3529          * /Agent directory, Check whether it needs to delete
3530          * from agent directory */
3531         if (unlikely(strcmp((char *)key, dotdot) == 0)) {
3532                 rc = osd_delete_from_remote_parent(env, osd_obj2dev(obj), obj,
3533                                                    oh);
3534                 if (rc != 0 && rc != -ENOENT) {
3535                         CERROR("%s: delete agent inode "DFID": rc = %d\n",
3536                                osd_name(osd), PFID(fid), rc);
3537                 }
3538
3539                 if (rc == -ENOENT)
3540                         rc = 0;
3541
3542                 GOTO(out, rc);
3543         }
3544 out:
3545
3546         LASSERT(osd_invariant(obj));
3547         RETURN(rc);
3548 }
3549
3550 /**
3551  *      Lookup index for \a key and copy record to \a rec.
3552  *
3553  *      \param  dt      osd index object
3554  *      \param  key     key for index
3555  *      \param  rec     record reference
3556  *
3557  *      \retval  +ve  success : exact mach
3558  *      \retval  0    return record with key not greater than \a key
3559  *      \retval -ve   failure
3560  */
3561 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
3562                                 struct dt_rec *rec, const struct dt_key *key,
3563                                 struct lustre_capa *capa)
3564 {
3565         struct osd_object      *obj = osd_dt_obj(dt);
3566         struct iam_path_descr  *ipd;
3567         struct iam_container   *bag = &obj->oo_dir->od_container;
3568         struct osd_thread_info *oti = osd_oti_get(env);
3569         struct iam_iterator    *it = &oti->oti_idx_it;
3570         struct iam_rec         *iam_rec;
3571         int                     rc;
3572
3573         ENTRY;
3574
3575         LASSERT(osd_invariant(obj));
3576         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3577         LASSERT(bag->ic_object == obj->oo_inode);
3578
3579         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
3580                 RETURN(-EACCES);
3581
3582         ipd = osd_idx_ipd_get(env, bag);
3583         if (IS_ERR(ipd))
3584                 RETURN(-ENOMEM);
3585
3586         /* got ipd now we can start iterator. */
3587         iam_it_init(it, bag, 0, ipd);
3588
3589         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3590                 /* swab quota uid/gid provided by caller */
3591                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3592                 key = (const struct dt_key *)&oti->oti_quota_id;
3593         }
3594
3595         rc = iam_it_get(it, (struct iam_key *)key);
3596         if (rc >= 0) {
3597                 if (S_ISDIR(obj->oo_inode->i_mode))
3598                         iam_rec = (struct iam_rec *)oti->oti_ldp;
3599                 else
3600                         iam_rec = (struct iam_rec *) rec;
3601
3602                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
3603
3604                 if (S_ISDIR(obj->oo_inode->i_mode))
3605                         osd_fid_unpack((struct lu_fid *) rec,
3606                                        (struct osd_fid_pack *)iam_rec);
3607                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
3608                         osd_quota_unpack(obj, rec);
3609         }
3610
3611         iam_it_put(it);
3612         iam_it_fini(it);
3613         osd_ipd_put(env, bag, ipd);
3614
3615         LINVRNT(osd_invariant(obj));
3616
3617         RETURN(rc);
3618 }
3619
3620 static int osd_index_declare_iam_insert(const struct lu_env *env,
3621                                         struct dt_object *dt,
3622                                         const struct dt_rec *rec,
3623                                         const struct dt_key *key,
3624                                         struct thandle *handle)
3625 {
3626         struct osd_thandle *oh;
3627
3628         LASSERT(handle != NULL);
3629
3630         oh = container_of0(handle, struct osd_thandle, ot_super);
3631         LASSERT(oh->ot_handle == NULL);
3632
3633         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3634                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
3635
3636         return 0;
3637 }
3638
3639 /**
3640  *      Inserts (key, value) pair in \a dt index object.
3641  *
3642  *      \param  dt      osd index object
3643  *      \param  key     key for index
3644  *      \param  rec     record reference
3645  *      \param  th      transaction handler
3646  *
3647  *      \retval  0  success
3648  *      \retval -ve failure
3649  */
3650 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
3651                                 const struct dt_rec *rec,
3652                                 const struct dt_key *key, struct thandle *th,
3653                                 struct lustre_capa *capa, int ignore_quota)
3654 {
3655         struct osd_object     *obj = osd_dt_obj(dt);
3656         struct iam_path_descr *ipd;
3657         struct osd_thandle    *oh;
3658         struct iam_container  *bag = &obj->oo_dir->od_container;
3659         struct osd_thread_info *oti = osd_oti_get(env);
3660         struct iam_rec         *iam_rec;
3661         int                     rc;
3662
3663         ENTRY;
3664
3665         LINVRNT(osd_invariant(obj));
3666         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3667         LASSERT(bag->ic_object == obj->oo_inode);
3668         LASSERT(th != NULL);
3669
3670         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3671                 RETURN(-EACCES);
3672
3673         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3674
3675         ipd = osd_idx_ipd_get(env, bag);
3676         if (unlikely(ipd == NULL))
3677                 RETURN(-ENOMEM);
3678
3679         oh = container_of0(th, struct osd_thandle, ot_super);
3680         LASSERT(oh->ot_handle != NULL);
3681         LASSERT(oh->ot_handle->h_transaction != NULL);
3682         if (S_ISDIR(obj->oo_inode->i_mode)) {
3683                 iam_rec = (struct iam_rec *)oti->oti_ldp;
3684                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
3685         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3686                 /* pack quota uid/gid */
3687                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3688                 key = (const struct dt_key *)&oti->oti_quota_id;
3689                 /* pack quota record */
3690                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
3691                 iam_rec = (struct iam_rec *)rec;
3692         } else {
3693                 iam_rec = (struct iam_rec *)rec;
3694         }
3695
3696         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
3697                         iam_rec, ipd);
3698         osd_ipd_put(env, bag, ipd);
3699         LINVRNT(osd_invariant(obj));
3700         RETURN(rc);
3701 }
3702
3703 /**
3704  * Calls ldiskfs_add_entry() to add directory entry
3705  * into the directory. This is required for
3706  * interoperability mode (b11826)
3707  *
3708  * \retval   0, on success
3709  * \retval -ve, on error
3710  */
3711 static int __osd_ea_add_rec(struct osd_thread_info *info,
3712                             struct osd_object *pobj, struct inode  *cinode,
3713                             const char *name, const struct dt_rec *fid,
3714                             struct htree_lock *hlock, struct thandle *th)
3715 {
3716         struct ldiskfs_dentry_param *ldp;
3717         struct dentry               *child;
3718         struct osd_thandle          *oth;
3719         int                          rc;
3720
3721         oth = container_of(th, struct osd_thandle, ot_super);
3722         LASSERT(oth->ot_handle != NULL);
3723         LASSERT(oth->ot_handle->h_transaction != NULL);
3724         LASSERT(pobj->oo_inode);
3725
3726         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3727         if (unlikely(pobj->oo_inode ==
3728                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
3729                 ldp->edp_magic = 0;
3730         else
3731                 osd_get_ldiskfs_dirent_param(ldp, fid);
3732         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
3733         child->d_fsdata = (void *)ldp;
3734         ll_vfs_dq_init(pobj->oo_inode);
3735         rc = osd_ldiskfs_add_entry(oth->ot_handle, child, cinode, hlock);
3736
3737         RETURN(rc);
3738 }
3739
3740 /**
3741  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
3742  * into the directory.Also sets flags into osd object to
3743  * indicate dot and dotdot are created. This is required for
3744  * interoperability mode (b11826)
3745  *
3746  * \param dir   directory for dot and dotdot fixup.
3747  * \param obj   child object for linking
3748  *
3749  * \retval   0, on success
3750  * \retval -ve, on error
3751  */
3752 static int osd_add_dot_dotdot(struct osd_thread_info *info,
3753                               struct osd_object *dir,
3754                               struct inode  *parent_dir, const char *name,
3755                               const struct dt_rec *dot_fid,
3756                               const struct dt_rec *dot_dot_fid,
3757                               struct thandle *th)
3758 {
3759         struct inode                *inode = dir->oo_inode;
3760         struct osd_thandle          *oth;
3761         int result = 0;
3762
3763         oth = container_of(th, struct osd_thandle, ot_super);
3764         LASSERT(oth->ot_handle->h_transaction != NULL);
3765         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
3766
3767         if (strcmp(name, dot) == 0) {
3768                 if (dir->oo_compat_dot_created) {
3769                         result = -EEXIST;
3770                 } else {
3771                         LASSERT(inode == parent_dir);
3772                         dir->oo_compat_dot_created = 1;
3773                         result = 0;
3774                 }
3775         } else if (strcmp(name, dotdot) == 0) {
3776                 if (!dir->oo_compat_dot_created)
3777                         return -EINVAL;
3778                 /* in case of rename, dotdot is already created */
3779                 if (dir->oo_compat_dotdot_created) {
3780                         return __osd_ea_add_rec(info, dir, parent_dir, name,
3781                                                 dot_dot_fid, NULL, th);
3782                 }
3783
3784                 result = osd_add_dot_dotdot_internal(info, dir->oo_inode,
3785                                                 parent_dir, dot_fid,
3786                                                 dot_dot_fid, oth);
3787                 if (result == 0)
3788                         dir->oo_compat_dotdot_created = 1;
3789         }
3790
3791         return result;
3792 }
3793
3794
3795 /**
3796  * It will call the appropriate osd_add* function and return the
3797  * value, return by respective functions.
3798  */
3799 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
3800                           struct inode *cinode, const char *name,
3801                           const struct dt_rec *fid, struct thandle *th)
3802 {
3803         struct osd_thread_info *info   = osd_oti_get(env);
3804         struct htree_lock      *hlock;
3805         int                     rc;
3806
3807         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
3808
3809         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
3810                                                    name[2] =='\0'))) {
3811                 if (hlock != NULL) {
3812                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3813                                            pobj->oo_inode, 0);
3814                 } else {
3815                         down_write(&pobj->oo_ext_idx_sem);
3816                 }
3817                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
3818                      (struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
3819                                         fid, th);
3820         } else {
3821                 if (hlock != NULL) {
3822                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3823                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
3824                 } else {
3825                         down_write(&pobj->oo_ext_idx_sem);
3826                 }
3827
3828                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
3829                         struct lu_fid *tfid = &info->oti_fid;
3830
3831                         *tfid = *(const struct lu_fid *)fid;
3832                         tfid->f_ver = ~0;
3833                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
3834                                               (const struct dt_rec *)tfid,
3835                                               hlock, th);
3836                 } else {
3837                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
3838                                               hlock, th);
3839                 }
3840         }
3841         if (hlock != NULL)
3842                 ldiskfs_htree_unlock(hlock);
3843         else
3844                 up_write(&pobj->oo_ext_idx_sem);
3845
3846         return rc;
3847 }
3848
3849 static void
3850 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
3851                       struct osd_idmap_cache *oic)
3852 {
3853         struct osd_scrub    *scrub = &dev->od_scrub;
3854         struct lu_fid       *fid   = &oic->oic_fid;
3855         struct osd_inode_id *id    = &oti->oti_id;
3856         int                  once  = 0;
3857         int                  rc;
3858         ENTRY;
3859
3860         if (!fid_is_norm(fid) && !fid_is_igif(fid))
3861                 RETURN_EXIT;
3862
3863 again:
3864         rc = osd_oi_lookup(oti, dev, fid, id, OI_CHECK_FLD);
3865         if (rc != 0 && rc != -ENOENT)
3866                 RETURN_EXIT;
3867
3868         if (rc == 0 && osd_id_eq(id, &oic->oic_lid))
3869                 RETURN_EXIT;
3870
3871         if (thread_is_running(&scrub->os_thread)) {
3872                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
3873                 /* There is race condition between osd_oi_lookup and OI scrub.
3874                  * The OI scrub finished just after osd_oi_lookup() failure.
3875                  * Under such case, it is unnecessary to trigger OI scrub again,
3876                  * but try to call osd_oi_lookup() again. */
3877                 if (unlikely(rc == -EAGAIN))
3878                         goto again;
3879
3880                 RETURN_EXIT;
3881         }
3882
3883         if (!dev->od_noscrub && ++once == 1) {
3884                 CDEBUG(D_LFSCK, "Trigger OI scrub by RPC for "DFID"\n",
3885                        PFID(fid));
3886                 rc = osd_scrub_start(dev);
3887                 LCONSOLE_ERROR("%.16s: trigger OI scrub by RPC for "DFID
3888                                ", rc = %d [2]\n",
3889                                LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
3890                                PFID(fid), rc);
3891                 if (rc == 0)
3892                         goto again;
3893         }
3894
3895         EXIT;
3896 }
3897
3898 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
3899                                struct osd_device *dev,
3900                                struct osd_idmap_cache *oic,
3901                                struct lu_fid *fid, __u32 ino)
3902 {
3903         struct lustre_mdt_attrs *lma   = &oti->oti_mdt_attrs;
3904         struct inode            *inode;
3905         int                      rc;
3906
3907         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
3908         inode = osd_iget(oti, dev, &oic->oic_lid);
3909         if (IS_ERR(inode)) {
3910                 fid_zero(&oic->oic_fid);
3911                 return PTR_ERR(inode);
3912         }
3913
3914         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, lma);
3915         iput(inode);
3916         if (rc != 0)
3917                 fid_zero(&oic->oic_fid);
3918         else
3919                 *fid = oic->oic_fid = lma->lma_self_fid;
3920         return rc;
3921 }
3922
3923 int osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
3924                      struct osd_inode_id *id, const struct lu_fid *fid)
3925 {
3926         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
3927                id->oii_ino, id->oii_gen, info);
3928         info->oti_cache.oic_lid = *id;
3929         info->oti_cache.oic_fid = *fid;
3930         info->oti_cache.oic_dev = osd;
3931
3932         return 0;
3933 }
3934
3935 /**
3936  * Calls ->lookup() to find dentry. From dentry get inode and
3937  * read inode's ea to get fid. This is required for  interoperability
3938  * mode (b11826)
3939  *
3940  * \retval   0, on success
3941  * \retval -ve, on error
3942  */
3943 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
3944                              struct dt_rec *rec, const struct dt_key *key)
3945 {
3946         struct inode               *dir    = obj->oo_inode;
3947         struct dentry              *dentry;
3948         struct ldiskfs_dir_entry_2 *de;
3949         struct buffer_head         *bh;
3950         struct lu_fid              *fid = (struct lu_fid *) rec;
3951         struct htree_lock          *hlock = NULL;
3952         int                         ino;
3953         int                         rc;
3954         ENTRY;
3955
3956         LASSERT(dir->i_op != NULL && dir->i_op->lookup != NULL);
3957
3958         dentry = osd_child_dentry_get(env, obj,
3959                                       (char *)key, strlen((char *)key));
3960
3961         if (obj->oo_hl_head != NULL) {
3962                 hlock = osd_oti_get(env)->oti_hlock;
3963                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3964                                    dir, LDISKFS_HLOCK_LOOKUP);
3965         } else {
3966                 down_read(&obj->oo_ext_idx_sem);
3967         }
3968
3969         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
3970         if (bh) {
3971                 struct osd_thread_info *oti = osd_oti_get(env);
3972                 struct osd_inode_id *id = &oti->oti_id;
3973                 struct osd_idmap_cache *oic = &oti->oti_cache;
3974                 struct osd_device *dev = osd_obj2dev(obj);
3975                 struct osd_scrub *scrub = &dev->od_scrub;
3976                 struct scrub_file *sf = &scrub->os_file;
3977
3978                 ino = le32_to_cpu(de->inode);
3979                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
3980                         brelse(bh);
3981                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
3982                         GOTO(out, rc);
3983                 }
3984
3985                 rc = osd_get_fid_from_dentry(de, rec);
3986
3987                 /* done with de, release bh */
3988                 brelse(bh);
3989                 if (rc != 0)
3990                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
3991                 else
3992                         osd_id_gen(id, ino, OSD_OII_NOGEN);
3993                 if (rc != 0) {
3994                         fid_zero(&oic->oic_fid);
3995                         GOTO(out, rc);
3996                 }
3997
3998                 rc = osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id,
3999                                       fid);
4000                 if (rc != 0)
4001                         GOTO(out, rc);
4002                 if ((scrub->os_pos_current <= ino) &&
4003                     ((sf->sf_flags & SF_INCONSISTENT) ||
4004                      (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
4005                      ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
4006                                       sf->sf_oi_bitmap)))
4007                         osd_consistency_check(oti, dev, oic);
4008         } else {
4009                 rc = -ENOENT;
4010         }
4011
4012         GOTO(out, rc);
4013
4014 out:
4015         if (hlock != NULL)
4016                 ldiskfs_htree_unlock(hlock);
4017         else
4018                 up_read(&obj->oo_ext_idx_sem);
4019         return rc;
4020 }
4021
4022 /**
4023  * Find the osd object for given fid.
4024  *
4025  * \param fid need to find the osd object having this fid
4026  *
4027  * \retval osd_object on success
4028  * \retval        -ve on error
4029  */
4030 struct osd_object *osd_object_find(const struct lu_env *env,
4031                                    struct dt_object *dt,
4032                                    const struct lu_fid *fid)
4033 {
4034         struct lu_device  *ludev = dt->do_lu.lo_dev;
4035         struct osd_object *child = NULL;
4036         struct lu_object  *luch;
4037         struct lu_object  *lo;
4038
4039         /*
4040          * at this point topdev might not exist yet
4041          * (i.e. MGS is preparing profiles). so we can
4042          * not rely on topdev and instead lookup with
4043          * our device passed as topdev. this can't work
4044          * if the object isn't cached yet (as osd doesn't
4045          * allocate lu_header). IOW, the object must be
4046          * in the cache, otherwise lu_object_alloc() crashes
4047          * -bzzz
4048          */
4049         luch = lu_object_find_at(env, ludev, fid, NULL);
4050         if (!IS_ERR(luch)) {
4051                 if (lu_object_exists(luch)) {
4052                         lo = lu_object_locate(luch->lo_header, ludev->ld_type);
4053                         if (lo != NULL)
4054                                 child = osd_obj(lo);
4055                         else
4056                                 LU_OBJECT_DEBUG(D_ERROR, env, luch,
4057                                                 "lu_object can't be located"
4058                                                 DFID"\n", PFID(fid));
4059
4060                         if (child == NULL) {
4061                                 lu_object_put(env, luch);
4062                                 CERROR("Unable to get osd_object\n");
4063                                 child = ERR_PTR(-ENOENT);
4064                         }
4065                 } else {
4066                         LU_OBJECT_DEBUG(D_ERROR, env, luch,
4067                                         "lu_object does not exists "DFID"\n",
4068                                         PFID(fid));
4069                         lu_object_put(env, luch);
4070                         child = ERR_PTR(-ENOENT);
4071                 }
4072         } else {
4073                 child = ERR_CAST(luch);
4074         }
4075
4076         return child;
4077 }
4078
4079 /**
4080  * Put the osd object once done with it.
4081  *
4082  * \param obj osd object that needs to be put
4083  */
4084 static inline void osd_object_put(const struct lu_env *env,
4085                                   struct osd_object *obj)
4086 {
4087         lu_object_put(env, &obj->oo_dt.do_lu);
4088 }
4089
4090 static int osd_index_declare_ea_insert(const struct lu_env *env,
4091                                        struct dt_object *dt,
4092                                        const struct dt_rec *rec,
4093                                        const struct dt_key *key,
4094                                        struct thandle *handle)
4095 {
4096         struct osd_thandle      *oh;
4097         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
4098         struct lu_fid           *fid = (struct lu_fid *)rec;
4099         int                     rc;
4100         ENTRY;
4101
4102         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4103         LASSERT(handle != NULL);
4104
4105         oh = container_of0(handle, struct osd_thandle, ot_super);
4106         LASSERT(oh->ot_handle == NULL);
4107
4108         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4109                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4110
4111         if (osd_dt_obj(dt)->oo_inode == NULL) {
4112                 const char *name  = (const char *)key;
4113                 /* Object is not being created yet. Only happens when
4114                  *     1. declare directory create
4115                  *     2. declare insert .
4116                  *     3. declare insert ..
4117                  */
4118                 LASSERT(strcmp(name, dotdot) == 0 || strcmp(name, dot) == 0);
4119         } else {
4120                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
4121
4122                 /* We ignore block quota on meta pool (MDTs), so needn't
4123                  * calculate how many blocks will be consumed by this index
4124                  * insert */
4125                 rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0,
4126                                            oh, true, true, NULL, false);
4127         }
4128
4129         if (fid == NULL)
4130                 RETURN(0);
4131
4132         rc = osd_remote_fid(env, osd, fid);
4133         if (rc <= 0)
4134                 RETURN(rc);
4135
4136         rc = 0;
4137
4138         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
4139                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
4140         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4141                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4142         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4143                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4144
4145         RETURN(rc);
4146 }
4147
4148 /**
4149  * Index add function for interoperability mode (b11826).
4150  * It will add the directory entry.This entry is needed to
4151  * maintain name->fid mapping.
4152  *
4153  * \param key it is key i.e. file entry to be inserted
4154  * \param rec it is value of given key i.e. fid
4155  *
4156  * \retval   0, on success
4157  * \retval -ve, on error
4158  */
4159 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
4160                                const struct dt_rec *rec,
4161                                const struct dt_key *key, struct thandle *th,
4162                                struct lustre_capa *capa, int ignore_quota)
4163 {
4164         struct osd_object       *obj = osd_dt_obj(dt);
4165         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
4166         struct lu_fid           *fid = (struct lu_fid *) rec;
4167         const char              *name = (const char *)key;
4168         struct osd_thread_info  *oti   = osd_oti_get(env);
4169         struct osd_inode_id     *id    = &oti->oti_id;
4170         struct inode            *child_inode = NULL;
4171         struct osd_object       *child = NULL;
4172         int                     rc;
4173         ENTRY;
4174
4175         LASSERT(osd_invariant(obj));
4176         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4177         LASSERT(th != NULL);
4178
4179         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4180
4181         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
4182                 RETURN(-EACCES);
4183
4184         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!", PFID(fid));
4185
4186         rc = osd_remote_fid(env, osd, fid);
4187         if (rc < 0) {
4188                 CERROR("%s: Can not find object "DFID" rc %d\n",
4189                        osd_name(osd), PFID(fid), rc);
4190                 RETURN(rc);
4191         }
4192
4193         if (rc == 1) {
4194                 /* Insert remote entry */
4195                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
4196                         struct osd_mdobj_map    *omm = osd->od_mdt_map;
4197                         struct osd_thandle      *oh;
4198
4199                         /* If parent on remote MDT, we need put this object
4200                          * under AGENT */
4201                         oh = container_of(th, typeof(*oh), ot_super);
4202                         rc = osd_add_to_remote_parent(env, osd, obj, oh);
4203                         if (rc != 0) {
4204                                 CERROR("%s: add "DFID" error: rc = %d\n",
4205                                        osd_name(osd),
4206                                        PFID(lu_object_fid(&dt->do_lu)), rc);
4207                                 RETURN(rc);
4208                         }
4209
4210                         child_inode = igrab(omm->omm_remote_parent->d_inode);
4211                 } else {
4212                         child_inode = osd_create_local_agent_inode(env, osd,
4213                                                                    obj, fid,
4214                                                                    th);
4215                         if (IS_ERR(child_inode))
4216                                 RETURN(PTR_ERR(child_inode));
4217                 }
4218         } else {
4219                 /* Insert local entry */
4220                 child = osd_object_find(env, dt, fid);
4221                 if (IS_ERR(child)) {
4222                         CERROR("%s: Can not find object "DFID"%u:%u: rc = %d\n",
4223                                osd_name(osd), PFID(fid),
4224                                id->oii_ino, id->oii_gen,
4225                                (int)PTR_ERR(child));
4226                         RETURN(PTR_ERR(child));
4227                 }
4228                 child_inode = igrab(child->oo_inode);
4229         }
4230
4231         rc = osd_ea_add_rec(env, obj, child_inode, name, rec, th);
4232
4233         iput(child_inode);
4234         if (child != NULL)
4235                 osd_object_put(env, child);
4236         LASSERT(osd_invariant(obj));
4237         RETURN(rc);
4238 }
4239
4240 /**
4241  *  Initialize osd Iterator for given osd index object.
4242  *
4243  *  \param  dt      osd index object
4244  */
4245
4246 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
4247                                      struct dt_object *dt,
4248                                      __u32 unused,
4249                                      struct lustre_capa *capa)
4250 {
4251         struct osd_it_iam      *it;
4252         struct osd_thread_info *oti = osd_oti_get(env);
4253         struct osd_object      *obj = osd_dt_obj(dt);
4254         struct lu_object       *lo  = &dt->do_lu;
4255         struct iam_path_descr  *ipd;
4256         struct iam_container   *bag = &obj->oo_dir->od_container;
4257
4258         LASSERT(lu_object_exists(lo));
4259
4260         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
4261                 return ERR_PTR(-EACCES);
4262
4263         it = &oti->oti_it;
4264         ipd = osd_it_ipd_get(env, bag);
4265         if (likely(ipd != NULL)) {
4266                 it->oi_obj = obj;
4267                 it->oi_ipd = ipd;
4268                 lu_object_get(lo);
4269                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
4270                 return (struct dt_it *)it;
4271         }
4272         return ERR_PTR(-ENOMEM);
4273 }
4274
4275 /**
4276  * free given Iterator.
4277  */
4278
4279 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
4280 {
4281         struct osd_it_iam *it = (struct osd_it_iam *)di;
4282         struct osd_object *obj = it->oi_obj;
4283
4284         iam_it_fini(&it->oi_it);
4285         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
4286         lu_object_put(env, &obj->oo_dt.do_lu);
4287 }
4288
4289 /**
4290  *  Move Iterator to record specified by \a key
4291  *
4292  *  \param  di      osd iterator
4293  *  \param  key     key for index
4294  *
4295  *  \retval +ve  di points to record with least key not larger than key
4296  *  \retval  0   di points to exact matched key
4297  *  \retval -ve  failure
4298  */
4299
4300 static int osd_it_iam_get(const struct lu_env *env,
4301                           struct dt_it *di, const struct dt_key *key)
4302 {
4303         struct osd_thread_info  *oti = osd_oti_get(env);
4304         struct osd_it_iam       *it = (struct osd_it_iam *)di;
4305
4306         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4307                 /* swab quota uid/gid */
4308                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4309                 key = (struct dt_key *)&oti->oti_quota_id;
4310         }
4311
4312         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
4313 }
4314
4315 /**
4316  *  Release Iterator
4317  *
4318  *  \param  di      osd iterator
4319  */
4320 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
4321 {
4322         struct osd_it_iam *it = (struct osd_it_iam *)di;
4323
4324         iam_it_put(&it->oi_it);
4325 }
4326
4327 /**
4328  *  Move iterator by one record
4329  *
4330  *  \param  di      osd iterator
4331  *
4332  *  \retval +1   end of container reached
4333  *  \retval  0   success
4334  *  \retval -ve  failure
4335  */
4336
4337 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
4338 {
4339         struct osd_it_iam *it = (struct osd_it_iam *)di;
4340
4341         return iam_it_next(&it->oi_it);
4342 }
4343
4344 /**
4345  * Return pointer to the key under iterator.
4346  */
4347
4348 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
4349                                  const struct dt_it *di)
4350 {
4351         struct osd_thread_info *oti = osd_oti_get(env);
4352         struct osd_it_iam      *it = (struct osd_it_iam *)di;
4353         struct osd_object      *obj = it->oi_obj;
4354         struct dt_key          *key;
4355
4356         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
4357
4358         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
4359                 /* swab quota uid/gid */
4360                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
4361                 key = (struct dt_key *)&oti->oti_quota_id;
4362         }
4363
4364         return key;
4365 }
4366
4367 /**
4368  * Return size of key under iterator (in bytes)
4369  */
4370
4371 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
4372 {
4373         struct osd_it_iam *it = (struct osd_it_iam *)di;
4374
4375         return iam_it_key_size(&it->oi_it);
4376 }
4377
4378 static inline void
4379 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
4380 {
4381         /* check if file type is required */
4382         if (ent->lde_attrs & LUDA_TYPE) {
4383                 struct luda_type *lt;
4384                 int align = sizeof(*lt) - 1;
4385
4386                 len = (len + align) & ~align;
4387                 lt = (struct luda_type *)(ent->lde_name + len);
4388                 lt->lt_type = cpu_to_le16(DTTOIF(type));
4389         }
4390
4391         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
4392 }
4393
4394 /**
4395  * build lu direct from backend fs dirent.
4396  */
4397
4398 static inline void
4399 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
4400                    char *name, __u16 namelen, __u16 type, __u32 attr)
4401 {
4402         ent->lde_attrs = attr | LUDA_FID;
4403         fid_cpu_to_le(&ent->lde_fid, fid);
4404
4405         ent->lde_hash = cpu_to_le64(offset);
4406         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
4407
4408         strncpy(ent->lde_name, name, namelen);
4409         ent->lde_name[namelen] = '\0';
4410         ent->lde_namelen = cpu_to_le16(namelen);
4411
4412         /* append lustre attributes */
4413         osd_it_append_attrs(ent, namelen, type);
4414 }
4415
4416 /**
4417  * Return pointer to the record under iterator.
4418  */
4419 static int osd_it_iam_rec(const struct lu_env *env,
4420                           const struct dt_it *di,
4421                           struct dt_rec *dtrec, __u32 attr)
4422 {
4423         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
4424         struct osd_thread_info *info = osd_oti_get(env);
4425         ENTRY;
4426
4427         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
4428                 const struct osd_fid_pack *rec;
4429                 struct lu_fid             *fid = &info->oti_fid;
4430                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
4431                 char                      *name;
4432                 int                        namelen;
4433                 __u64                      hash;
4434                 int                        rc;
4435
4436                 name = (char *)iam_it_key_get(&it->oi_it);
4437                 if (IS_ERR(name))
4438                         RETURN(PTR_ERR(name));
4439
4440                 namelen = iam_it_key_size(&it->oi_it);
4441
4442                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
4443                 if (IS_ERR(rec))
4444                         RETURN(PTR_ERR(rec));
4445
4446                 rc = osd_fid_unpack(fid, rec);
4447                 if (rc)
4448                         RETURN(rc);
4449
4450                 hash = iam_it_store(&it->oi_it);
4451
4452                 /* IAM does not store object type in IAM index (dir) */
4453                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
4454                                    0, LUDA_FID);
4455         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4456                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4457                            (struct iam_rec *)dtrec);
4458                 osd_quota_unpack(it->oi_obj, dtrec);
4459         } else {
4460                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4461                            (struct iam_rec *)dtrec);
4462         }
4463
4464         RETURN(0);
4465 }
4466
4467 /**
4468  * Returns cookie for current Iterator position.
4469  */
4470 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
4471 {
4472         struct osd_it_iam *it = (struct osd_it_iam *)di;
4473
4474         return iam_it_store(&it->oi_it);
4475 }
4476
4477 /**
4478  * Restore iterator from cookie.
4479  *
4480  * \param  di      osd iterator
4481  * \param  hash    Iterator location cookie
4482  *
4483  * \retval +ve  di points to record with least key not larger than key.
4484  * \retval  0   di points to exact matched key
4485  * \retval -ve  failure
4486  */
4487
4488 static int osd_it_iam_load(const struct lu_env *env,
4489                            const struct dt_it *di, __u64 hash)
4490 {
4491         struct osd_it_iam *it = (struct osd_it_iam *)di;
4492
4493         return iam_it_load(&it->oi_it, hash);
4494 }
4495
4496 static const struct dt_index_operations osd_index_iam_ops = {
4497         .dio_lookup         = osd_index_iam_lookup,
4498         .dio_declare_insert = osd_index_declare_iam_insert,
4499         .dio_insert         = osd_index_iam_insert,
4500         .dio_declare_delete = osd_index_declare_iam_delete,
4501         .dio_delete         = osd_index_iam_delete,
4502         .dio_it     = {
4503                 .init     = osd_it_iam_init,
4504                 .fini     = osd_it_iam_fini,
4505                 .get      = osd_it_iam_get,
4506                 .put      = osd_it_iam_put,
4507                 .next     = osd_it_iam_next,
4508                 .key      = osd_it_iam_key,
4509                 .key_size = osd_it_iam_key_size,
4510                 .rec      = osd_it_iam_rec,
4511                 .store    = osd_it_iam_store,
4512                 .load     = osd_it_iam_load
4513         }
4514 };
4515
4516
4517 /**
4518  * Creates or initializes iterator context.
4519  *
4520  * \retval struct osd_it_ea, iterator structure on success
4521  *
4522  */
4523 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
4524                                     struct dt_object *dt,
4525                                     __u32 attr,
4526                                     struct lustre_capa *capa)
4527 {
4528         struct osd_object       *obj  = osd_dt_obj(dt);
4529         struct osd_thread_info  *info = osd_oti_get(env);
4530         struct osd_it_ea        *it   = &info->oti_it_ea;
4531         struct file             *file = &it->oie_file;
4532         struct lu_object        *lo   = &dt->do_lu;
4533         struct dentry           *obj_dentry = &info->oti_it_dentry;
4534         ENTRY;
4535         LASSERT(lu_object_exists(lo));
4536
4537         obj_dentry->d_inode = obj->oo_inode;
4538         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
4539         obj_dentry->d_name.hash = 0;
4540
4541         it->oie_rd_dirent       = 0;
4542         it->oie_it_dirent       = 0;
4543         it->oie_dirent          = NULL;
4544         it->oie_buf             = info->oti_it_ea_buf;
4545         it->oie_obj             = obj;
4546
4547         /* Reset the "file" totally to avoid to reuse any old value from
4548          * former readdir handling, the "file->f_pos" should be zero. */
4549         memset(file, 0, sizeof(*file));
4550         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
4551         if (attr & LUDA_64BITHASH)
4552                 file->f_mode    = FMODE_64BITHASH;
4553         else
4554                 file->f_mode    = FMODE_32BITHASH;
4555         file->f_dentry          = obj_dentry;
4556         file->f_mapping         = obj->oo_inode->i_mapping;
4557         file->f_op              = obj->oo_inode->i_fop;
4558         set_file_inode(file, obj->oo_inode);
4559
4560         lu_object_get(lo);
4561         RETURN((struct dt_it *) it);
4562 }
4563
4564 /**
4565  * Destroy or finishes iterator context.
4566  *
4567  * \param di iterator structure to be destroyed
4568  */
4569 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
4570 {
4571         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4572         struct osd_object    *obj  = it->oie_obj;
4573         struct inode       *inode  = obj->oo_inode;
4574
4575         ENTRY;
4576         it->oie_file.f_op->release(inode, &it->oie_file);
4577         lu_object_put(env, &obj->oo_dt.do_lu);
4578         EXIT;
4579 }
4580
4581 /**
4582  * It position the iterator at given key, so that next lookup continues from
4583  * that key Or it is similar to dio_it->load() but based on a key,
4584  * rather than file position.
4585  *
4586  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
4587  * to the beginning.
4588  *
4589  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
4590  */
4591 static int osd_it_ea_get(const struct lu_env *env,
4592                          struct dt_it *di, const struct dt_key *key)
4593 {
4594         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4595
4596         ENTRY;
4597         LASSERT(((const char *)key)[0] == '\0');
4598         it->oie_file.f_pos      = 0;
4599         it->oie_rd_dirent       = 0;
4600         it->oie_it_dirent       = 0;
4601         it->oie_dirent          = NULL;
4602
4603         RETURN(+1);
4604 }
4605
4606 /**
4607  * Does nothing
4608  */
4609 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
4610 {
4611 }
4612
4613 /**
4614  * It is called internally by ->readdir(). It fills the
4615  * iterator's in-memory data structure with required
4616  * information i.e. name, namelen, rec_size etc.
4617  *
4618  * \param buf in which information to be filled in.
4619  * \param name name of the file in given dir
4620  *
4621  * \retval 0 on success
4622  * \retval 1 on buffer full
4623  */
4624 static int osd_ldiskfs_filldir(char *buf, const char *name, int namelen,
4625                                loff_t offset, __u64 ino,
4626                                unsigned d_type)
4627 {
4628         struct osd_it_ea        *it   = (struct osd_it_ea *)buf;
4629         struct osd_object       *obj  = it->oie_obj;
4630         struct osd_it_ea_dirent *ent  = it->oie_dirent;
4631         struct lu_fid           *fid  = &ent->oied_fid;
4632         struct osd_fid_pack     *rec;
4633         ENTRY;
4634
4635         /* this should never happen */
4636         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
4637                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
4638                 RETURN(-EIO);
4639         }
4640
4641         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
4642             OSD_IT_EA_BUFSIZE)
4643                 RETURN(1);
4644
4645         /* "." is just the object itself. */
4646         if (namelen == 1 && name[0] == '.') {
4647                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4648         } else if (d_type & LDISKFS_DIRENT_LUFID) {
4649                 rec = (struct osd_fid_pack*) (name + namelen + 1);
4650                 if (osd_fid_unpack(fid, rec) != 0)
4651                         fid_zero(fid);
4652         } else {
4653                 fid_zero(fid);
4654         }
4655         d_type &= ~LDISKFS_DIRENT_LUFID;
4656
4657         /* NOT export local root. */
4658         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
4659                 ino = obj->oo_inode->i_ino;
4660                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4661         }
4662
4663         ent->oied_ino     = ino;
4664         ent->oied_off     = offset;
4665         ent->oied_namelen = namelen;
4666         ent->oied_type    = d_type;
4667
4668         memcpy(ent->oied_name, name, namelen);
4669
4670         it->oie_rd_dirent++;
4671         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
4672         RETURN(0);
4673 }
4674
4675 /**
4676  * Calls ->readdir() to load a directory entry at a time
4677  * and stored it in iterator's in-memory data structure.
4678  *
4679  * \param di iterator's in memory structure
4680  *
4681  * \retval   0 on success
4682  * \retval -ve on error
4683  */
4684 static int osd_ldiskfs_it_fill(const struct lu_env *env,
4685                                const struct dt_it *di)
4686 {
4687         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
4688         struct osd_object  *obj   = it->oie_obj;
4689         struct inode       *inode = obj->oo_inode;
4690         struct htree_lock  *hlock = NULL;
4691         int                 result = 0;
4692
4693         ENTRY;
4694         it->oie_dirent = it->oie_buf;
4695         it->oie_rd_dirent = 0;
4696
4697         if (obj->oo_hl_head != NULL) {
4698                 hlock = osd_oti_get(env)->oti_hlock;
4699                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4700                                    inode, LDISKFS_HLOCK_READDIR);
4701         } else {
4702                 down_read(&obj->oo_ext_idx_sem);
4703         }
4704
4705         result = inode->i_fop->readdir(&it->oie_file, it,
4706                                        (filldir_t) osd_ldiskfs_filldir);
4707
4708         if (hlock != NULL)
4709                 ldiskfs_htree_unlock(hlock);
4710         else
4711                 up_read(&obj->oo_ext_idx_sem);
4712
4713         if (it->oie_rd_dirent == 0) {
4714                 result = -EIO;
4715         } else {
4716                 it->oie_dirent = it->oie_buf;
4717                 it->oie_it_dirent = 1;
4718         }
4719
4720         RETURN(result);
4721 }
4722
4723 /**
4724  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4725  * to load a directory entry at a time and stored it in
4726  * iterator's in-memory data structure.
4727  *
4728  * \param di iterator's in memory structure
4729  *
4730  * \retval +ve iterator reached to end
4731  * \retval   0 iterator not reached to end
4732  * \retval -ve on error
4733  */
4734 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
4735 {
4736         struct osd_it_ea *it = (struct osd_it_ea *)di;
4737         int rc;
4738
4739         ENTRY;
4740
4741         if (it->oie_it_dirent < it->oie_rd_dirent) {
4742                 it->oie_dirent =
4743                         (void *) it->oie_dirent +
4744                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
4745                                        it->oie_dirent->oied_namelen);
4746                 it->oie_it_dirent++;
4747                 RETURN(0);
4748         } else {
4749                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
4750                         rc = +1;
4751                 else
4752                         rc = osd_ldiskfs_it_fill(env, di);
4753         }
4754
4755         RETURN(rc);
4756 }
4757
4758 /**
4759  * Returns the key at current position from iterator's in memory structure.
4760  *
4761  * \param di iterator's in memory structure
4762  *
4763  * \retval key i.e. struct dt_key on success
4764  */
4765 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
4766                                     const struct dt_it *di)
4767 {
4768         struct osd_it_ea *it = (struct osd_it_ea *)di;
4769
4770         return (struct dt_key *)it->oie_dirent->oied_name;
4771 }
4772
4773 /**
4774  * Returns the key's size at current position from iterator's in memory structure.
4775  *
4776  * \param di iterator's in memory structure
4777  *
4778  * \retval key_size i.e. struct dt_key on success
4779  */
4780 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
4781 {
4782         struct osd_it_ea *it = (struct osd_it_ea *)di;
4783
4784         return it->oie_dirent->oied_namelen;
4785 }
4786
4787 static int
4788 osd_dirent_update(handle_t *jh, struct super_block *sb,
4789                   struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4790                   struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de)
4791 {
4792         struct osd_fid_pack *rec;
4793         int                  rc;
4794         ENTRY;
4795
4796         LASSERT(de->file_type & LDISKFS_DIRENT_LUFID);
4797         LASSERT(de->rec_len >= de->name_len + sizeof(struct osd_fid_pack));
4798
4799         rc = ldiskfs_journal_get_write_access(jh, bh);
4800         if (rc != 0) {
4801                 CERROR("%.16s: fail to write access for update dirent: "
4802                        "name = %.*s, rc = %d\n",
4803                        LDISKFS_SB(sb)->s_es->s_volume_name,
4804                        ent->oied_namelen, ent->oied_name, rc);
4805                 RETURN(rc);
4806         }
4807
4808         rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4809         fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4810         rc = ldiskfs_journal_dirty_metadata(jh, bh);
4811         if (rc != 0)
4812                 CERROR("%.16s: fail to dirty metadata for update dirent: "
4813                        "name = %.*s, rc = %d\n",
4814                        LDISKFS_SB(sb)->s_es->s_volume_name,
4815                        ent->oied_namelen, ent->oied_name, rc);
4816
4817         RETURN(rc);
4818 }
4819
4820 static inline int
4821 osd_dirent_has_space(__u16 reclen, __u16 namelen, unsigned blocksize)
4822 {
4823         if (ldiskfs_rec_len_from_disk(reclen, blocksize) >=
4824             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
4825                 return 1;
4826         else
4827                 return 0;
4828 }
4829
4830 static inline int
4831 osd_dot_dotdot_has_space(struct ldiskfs_dir_entry_2 *de, int dot_dotdot)
4832 {
4833         LASSERTF(dot_dotdot == 1 || dot_dotdot == 2,
4834                  "dot_dotdot = %d\n", dot_dotdot);
4835
4836         if (LDISKFS_DIR_REC_LEN(de) >=
4837             __LDISKFS_DIR_REC_LEN(dot_dotdot + 1 + sizeof(struct osd_fid_pack)))
4838                 return 1;
4839         else
4840                 return 0;
4841 }
4842
4843 static int
4844 osd_dirent_reinsert(const struct lu_env *env, handle_t *jh,
4845                     struct inode *dir, struct inode *inode,
4846                     struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4847                     struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de,
4848                     struct htree_lock *hlock)
4849 {
4850         struct dentry               *dentry;
4851         struct osd_fid_pack         *rec;
4852         struct ldiskfs_dentry_param *ldp;
4853         int                          rc;
4854         ENTRY;
4855
4856         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
4857                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
4858                 RETURN(0);
4859
4860         /* There is enough space to hold the FID-in-dirent. */
4861         if (osd_dirent_has_space(de->rec_len, ent->oied_namelen,
4862                                  dir->i_sb->s_blocksize)) {
4863                 rc = ldiskfs_journal_get_write_access(jh, bh);
4864                 if (rc != 0) {
4865                         CERROR("%.16s: fail to write access for reinsert "
4866                                "dirent: name = %.*s, rc = %d\n",
4867                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4868                                ent->oied_namelen, ent->oied_name, rc);
4869                         RETURN(rc);
4870                 }
4871
4872                 de->name[de->name_len] = 0;
4873                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4874                 rec->fp_len = sizeof(struct lu_fid) + 1;
4875                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4876                 de->file_type |= LDISKFS_DIRENT_LUFID;
4877
4878                 rc = ldiskfs_journal_dirty_metadata(jh, bh);
4879                 if (rc != 0)
4880                         CERROR("%.16s: fail to dirty metadata for reinsert "
4881                                "dirent: name = %.*s, rc = %d\n",
4882                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4883                                ent->oied_namelen, ent->oied_name, rc);
4884
4885                 RETURN(rc);
4886         }
4887
4888         rc = ldiskfs_delete_entry(jh, dir, de, bh);
4889         if (rc != 0) {
4890                 CERROR("%.16s: fail to delete entry for reinsert dirent: "
4891                        "name = %.*s, rc = %d\n",
4892                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4893                        ent->oied_namelen, ent->oied_name, rc);
4894                 RETURN(rc);
4895         }
4896
4897         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
4898                                            ent->oied_namelen);
4899         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
4900         osd_get_ldiskfs_dirent_param(ldp, (const struct dt_rec *)fid);
4901         dentry->d_fsdata = (void *)ldp;
4902         ll_vfs_dq_init(dir);
4903         rc = osd_ldiskfs_add_entry(jh, dentry, inode, hlock);
4904         /* It is too bad, we cannot reinsert the name entry back.
4905          * That means we lose it! */
4906         if (rc != 0)
4907                 CERROR("%.16s: fail to insert entry for reinsert dirent: "
4908                        "name = %.*s, rc = %d\n",
4909                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4910                        ent->oied_namelen, ent->oied_name, rc);
4911
4912         RETURN(rc);
4913 }
4914
4915 static int
4916 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
4917                         struct osd_it_ea *it, struct lu_fid *fid,
4918                         struct osd_inode_id *id, __u32 *attr)
4919 {
4920         struct osd_thread_info     *info        = osd_oti_get(env);
4921         struct lustre_mdt_attrs    *lma         = &info->oti_mdt_attrs;
4922         struct osd_device          *dev         = osd_obj2dev(obj);
4923         struct super_block         *sb          = osd_sb(dev);
4924         const char                 *devname     =
4925                                         LDISKFS_SB(sb)->s_es->s_volume_name;
4926         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
4927         struct inode               *dir         = obj->oo_inode;
4928         struct htree_lock          *hlock       = NULL;
4929         struct buffer_head         *bh          = NULL;
4930         handle_t                   *jh          = NULL;
4931         struct ldiskfs_dir_entry_2 *de;
4932         struct dentry              *dentry;
4933         struct inode               *inode;
4934         int                         credits;
4935         int                         rc;
4936         int                         dot_dotdot  = 0;
4937         bool                        dirty       = false;
4938         ENTRY;
4939
4940         if (ent->oied_name[0] == '.') {
4941                 if (ent->oied_namelen == 1)
4942                         dot_dotdot = 1;
4943                 else if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
4944                         dot_dotdot = 2;
4945         }
4946
4947         dentry = osd_child_dentry_get(env, obj, ent->oied_name,
4948                                       ent->oied_namelen);
4949
4950         /* We need to ensure that the name entry is still valid.
4951          * Because it may be removed or renamed by other already.
4952          *
4953          * The unlink or rename operation will start journal before PDO lock,
4954          * so to avoid deadlock, here we need to start journal handle before
4955          * related PDO lock also. But because we do not know whether there
4956          * will be something to be repaired before PDO lock, we just start
4957          * journal without conditions.
4958          *
4959          * We may need to remove the name entry firstly, then insert back.
4960          * One credit is for user quota file update.
4961          * One credit is for group quota file update.
4962          * Two credits are for dirty inode. */
4963         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
4964                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
4965
4966 again:
4967         if (dev->od_dirent_journal) {
4968                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
4969                 if (IS_ERR(jh)) {
4970                         rc = PTR_ERR(jh);
4971                         CERROR("%.16s: fail to start trans for dirent "
4972                                "check_repair: credits %d, name %.*s, rc %d\n",
4973                                devname, credits, ent->oied_namelen,
4974                                ent->oied_name, rc);
4975                         RETURN(rc);
4976                 }
4977
4978                 if (obj->oo_hl_head != NULL) {
4979                         hlock = osd_oti_get(env)->oti_hlock;
4980                         /* "0" means exclusive lock for the whole directory.
4981                          * We need to prevent others access such name entry
4982                          * during the delete + insert. Neither HLOCK_ADD nor
4983                          * HLOCK_DEL cannot guarantee the atomicity. */
4984                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
4985                 } else {
4986                         down_write(&obj->oo_ext_idx_sem);
4987                 }
4988         } else {
4989                 if (obj->oo_hl_head != NULL) {
4990                         hlock = osd_oti_get(env)->oti_hlock;
4991                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
4992                                            LDISKFS_HLOCK_LOOKUP);
4993                 } else {
4994                         down_read(&obj->oo_ext_idx_sem);
4995                 }
4996         }
4997
4998         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
4999         /* For dot/dotdot entry, if there is not enough space to hold the
5000          * FID-in-dirent, just keep them there. It only happens when the
5001          * device upgraded from 1.8 or restored from MDT file-level backup.
5002          * For the whole directory, only dot/dotdot entry have no FID-in-dirent
5003          * and needs to get FID from LMA when readdir, it will not affect the
5004          * performance much. */
5005         if ((bh == NULL) || (le32_to_cpu(de->inode) != ent->oied_ino) ||
5006             (dot_dotdot != 0 && !osd_dot_dotdot_has_space(de, dot_dotdot))) {
5007                 *attr |= LUDA_IGNORE;
5008                 GOTO(out_journal, rc = 0);
5009         }
5010
5011         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
5012         inode = osd_iget(info, dev, id);
5013         if (IS_ERR(inode)) {
5014                 rc = PTR_ERR(inode);
5015                 if (rc == -ENOENT || rc == -ESTALE) {
5016                         *attr |= LUDA_IGNORE;
5017                         rc = 0;
5018                 }
5019
5020                 GOTO(out_journal, rc);
5021         }
5022
5023         /* skip the REMOTE_PARENT_DIR. */
5024         if (inode == dev->od_mdt_map->omm_remote_parent->d_inode)
5025                 GOTO(out_inode, rc = 0);
5026
5027         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
5028         if (rc == 0) {
5029                 LASSERT(!(lma->lma_compat & LMAC_NOT_IN_OI));
5030
5031                 if (fid_is_sane(fid)) {
5032                         /* FID-in-dirent is valid. */
5033                         if (lu_fid_eq(fid, &lma->lma_self_fid))
5034                                 GOTO(out_inode, rc = 0);
5035
5036                         /* Do not repair under dryrun mode. */
5037                         if (*attr & LUDA_VERIFY_DRYRUN) {
5038                                 *attr |= LUDA_REPAIR;
5039                                 GOTO(out_inode, rc = 0);
5040                         }
5041
5042                         if (!dev->od_dirent_journal) {
5043                                 iput(inode);
5044                                 brelse(bh);
5045                                 if (hlock != NULL)
5046                                         ldiskfs_htree_unlock(hlock);
5047                                 else
5048                                         up_read(&obj->oo_ext_idx_sem);
5049                                 dev->od_dirent_journal = 1;
5050                                 goto again;
5051                         }
5052
5053                         *fid = lma->lma_self_fid;
5054                         dirty = true;
5055                         /* Update the FID-in-dirent. */
5056                         rc = osd_dirent_update(jh, sb, ent, fid, bh, de);
5057                         if (rc == 0)
5058                                 *attr |= LUDA_REPAIR;
5059                 } else {
5060                         /* Do not repair under dryrun mode. */
5061                         if (*attr & LUDA_VERIFY_DRYRUN) {
5062                                 *fid = lma->lma_self_fid;
5063                                 *attr |= LUDA_REPAIR;
5064                                 GOTO(out_inode, rc = 0);
5065                         }
5066
5067                         if (!dev->od_dirent_journal) {
5068                                 iput(inode);
5069                                 brelse(bh);
5070                                 if (hlock != NULL)
5071                                         ldiskfs_htree_unlock(hlock);
5072                                 else
5073                                         up_read(&obj->oo_ext_idx_sem);
5074                                 dev->od_dirent_journal = 1;
5075                                 goto again;
5076                         }
5077
5078                         *fid = lma->lma_self_fid;
5079                         dirty = true;
5080                         /* Append the FID-in-dirent. */
5081                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5082                                                  fid, bh, de, hlock);
5083                         if (rc == 0)
5084                                 *attr |= LUDA_REPAIR;
5085                 }
5086         } else if (rc == -ENODATA) {
5087                 /* Do not repair under dryrun mode. */
5088                 if (*attr & LUDA_VERIFY_DRYRUN) {
5089                         if (fid_is_sane(fid)) {
5090                                 *attr |= LUDA_REPAIR;
5091                         } else {
5092                                 lu_igif_build(fid, inode->i_ino,
5093                                               inode->i_generation);
5094                                 *attr |= LUDA_UPGRADE;
5095                         }
5096                         GOTO(out_inode, rc = 0);
5097                 }
5098
5099                 if (!dev->od_dirent_journal) {
5100                         iput(inode);
5101                         brelse(bh);
5102                         if (hlock != NULL)
5103                                 ldiskfs_htree_unlock(hlock);
5104                         else
5105                                 up_read(&obj->oo_ext_idx_sem);
5106                         dev->od_dirent_journal = 1;
5107                         goto again;
5108                 }
5109
5110                 dirty = true;
5111                 if (unlikely(fid_is_sane(fid))) {
5112                         /* FID-in-dirent exists, but FID-in-LMA is lost.
5113                          * Trust the FID-in-dirent, and add FID-in-LMA. */
5114                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
5115                         if (rc == 0)
5116                                 *attr |= LUDA_REPAIR;
5117                 } else {
5118                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
5119                         /* It is probably IGIF object. Only aappend the
5120                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
5121                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5122                                                  fid, bh, de, hlock);
5123                         if (rc == 0)
5124                                 *attr |= LUDA_UPGRADE;
5125                 }
5126         }
5127
5128         GOTO(out_inode, rc);
5129
5130 out_inode:
5131         iput(inode);
5132
5133 out_journal:
5134         brelse(bh);
5135         if (hlock != NULL) {
5136                 ldiskfs_htree_unlock(hlock);
5137         } else {
5138                 if (dev->od_dirent_journal)
5139                         up_write(&obj->oo_ext_idx_sem);
5140                 else
5141                         up_read(&obj->oo_ext_idx_sem);
5142         }
5143         if (jh != NULL)
5144                 ldiskfs_journal_stop(jh);
5145         if (rc >= 0 && !dirty)
5146                 dev->od_dirent_journal = 0;
5147         return rc;
5148 }
5149
5150 /**
5151  * Returns the value at current position from iterator's in memory structure.
5152  *
5153  * \param di struct osd_it_ea, iterator's in memory structure
5154  * \param attr attr requested for dirent.
5155  * \param lde lustre dirent
5156  *
5157  * \retval   0 no error and \param lde has correct lustre dirent.
5158  * \retval -ve on error
5159  */
5160 static inline int osd_it_ea_rec(const struct lu_env *env,
5161                                 const struct dt_it *di,
5162                                 struct dt_rec *dtrec, __u32 attr)
5163 {
5164         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
5165         struct osd_object      *obj   = it->oie_obj;
5166         struct osd_device      *dev   = osd_obj2dev(obj);
5167         struct osd_scrub       *scrub = &dev->od_scrub;
5168         struct scrub_file      *sf    = &scrub->os_file;
5169         struct osd_thread_info *oti   = osd_oti_get(env);
5170         struct osd_inode_id    *id    = &oti->oti_id;
5171         struct osd_idmap_cache *oic   = &oti->oti_cache;
5172         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
5173         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
5174         __u32                   ino   = it->oie_dirent->oied_ino;
5175         int                     rc    = 0;
5176         ENTRY;
5177
5178         if (attr & LUDA_VERIFY) {
5179                 attr |= LUDA_TYPE;
5180                 if (unlikely(ino == osd_sb(dev)->s_root->d_inode->i_ino)) {
5181                         attr |= LUDA_IGNORE;
5182                         rc = 0;
5183                 } else {
5184                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
5185                                                      &attr);
5186                 }
5187         } else {
5188                 attr &= ~LU_DIRENT_ATTRS_MASK;
5189                 if (!fid_is_sane(fid)) {
5190                         if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
5191                                 RETURN(-ENOENT);
5192
5193                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
5194                 } else {
5195                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5196                 }
5197         }
5198
5199         /* Pack the entry anyway, at least the offset is right. */
5200         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
5201                            it->oie_dirent->oied_name,
5202                            it->oie_dirent->oied_namelen,
5203                            it->oie_dirent->oied_type, attr);
5204
5205         if (rc < 0)
5206                 RETURN(rc);
5207
5208         if (osd_remote_fid(env, dev, fid))
5209                 RETURN(0);
5210
5211         if (likely(!(attr & LUDA_IGNORE)))
5212                 rc = osd_add_oi_cache(oti, dev, id, fid);
5213
5214         if (!(attr & LUDA_VERIFY) &&
5215             (scrub->os_pos_current <= ino) &&
5216             ((sf->sf_flags & SF_INCONSISTENT) ||
5217              (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
5218              ldiskfs_test_bit(osd_oi_fid2idx(dev, fid), sf->sf_oi_bitmap)))
5219                 osd_consistency_check(oti, dev, oic);
5220
5221         RETURN(rc);
5222 }
5223
5224 /**
5225  * Returns a cookie for current position of the iterator head, so that
5226  * user can use this cookie to load/start the iterator next time.
5227  *
5228  * \param di iterator's in memory structure
5229  *
5230  * \retval cookie for current position, on success
5231  */
5232 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
5233 {
5234         struct osd_it_ea *it = (struct osd_it_ea *)di;
5235
5236         return it->oie_dirent->oied_off;
5237 }
5238
5239 /**
5240  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5241  * to load a directory entry at a time and stored it i inn,
5242  * in iterator's in-memory data structure.
5243  *
5244  * \param di struct osd_it_ea, iterator's in memory structure
5245  *
5246  * \retval +ve on success
5247  * \retval -ve on error
5248  */
5249 static int osd_it_ea_load(const struct lu_env *env,
5250                           const struct dt_it *di, __u64 hash)
5251 {
5252         struct osd_it_ea *it = (struct osd_it_ea *)di;
5253         int rc;
5254
5255         ENTRY;
5256         it->oie_file.f_pos = hash;
5257
5258         rc =  osd_ldiskfs_it_fill(env, di);
5259         if (rc == 0)
5260                 rc = +1;
5261
5262         RETURN(rc);
5263 }
5264
5265 /**
5266  * Index lookup function for interoperability mode (b11826).
5267  *
5268  * \param key,  key i.e. file name to be searched
5269  *
5270  * \retval +ve, on success
5271  * \retval -ve, on error
5272  */
5273 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
5274                                struct dt_rec *rec, const struct dt_key *key,
5275                                struct lustre_capa *capa)
5276 {
5277         struct osd_object *obj = osd_dt_obj(dt);
5278         int rc = 0;
5279
5280         ENTRY;
5281
5282         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
5283         LINVRNT(osd_invariant(obj));
5284
5285         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
5286                 return -EACCES;
5287
5288         rc = osd_ea_lookup_rec(env, obj, rec, key);
5289         if (rc == 0)
5290                 rc = +1;
5291         RETURN(rc);
5292 }
5293
5294 /**
5295  * Index and Iterator operations for interoperability
5296  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
5297  */
5298 static const struct dt_index_operations osd_index_ea_ops = {
5299         .dio_lookup         = osd_index_ea_lookup,
5300         .dio_declare_insert = osd_index_declare_ea_insert,
5301         .dio_insert         = osd_index_ea_insert,
5302         .dio_declare_delete = osd_index_declare_ea_delete,
5303         .dio_delete         = osd_index_ea_delete,
5304         .dio_it     = {
5305                 .init     = osd_it_ea_init,
5306                 .fini     = osd_it_ea_fini,
5307                 .get      = osd_it_ea_get,
5308                 .put      = osd_it_ea_put,
5309                 .next     = osd_it_ea_next,
5310                 .key      = osd_it_ea_key,
5311                 .key_size = osd_it_ea_key_size,
5312                 .rec      = osd_it_ea_rec,
5313                 .store    = osd_it_ea_store,
5314                 .load     = osd_it_ea_load
5315         }
5316 };
5317
5318 static void *osd_key_init(const struct lu_context *ctx,
5319                           struct lu_context_key *key)
5320 {
5321         struct osd_thread_info *info;
5322
5323         OBD_ALLOC_PTR(info);
5324         if (info == NULL)
5325                 return ERR_PTR(-ENOMEM);
5326
5327         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5328         if (info->oti_it_ea_buf == NULL)
5329                 goto out_free_info;
5330
5331         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
5332
5333         info->oti_hlock = ldiskfs_htree_lock_alloc();
5334         if (info->oti_hlock == NULL)
5335                 goto out_free_ea;
5336
5337         return info;
5338
5339  out_free_ea:
5340         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5341  out_free_info:
5342         OBD_FREE_PTR(info);
5343         return ERR_PTR(-ENOMEM);
5344 }
5345
5346 static void osd_key_fini(const struct lu_context *ctx,
5347                          struct lu_context_key *key, void* data)
5348 {
5349         struct osd_thread_info *info = data;
5350
5351         if (info->oti_hlock != NULL)
5352                 ldiskfs_htree_lock_free(info->oti_hlock);
5353         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5354         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
5355         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
5356         OBD_FREE_PTR(info);
5357 }
5358
5359 static void osd_key_exit(const struct lu_context *ctx,
5360                          struct lu_context_key *key, void *data)
5361 {
5362         struct osd_thread_info *info = data;
5363
5364         LASSERT(info->oti_r_locks == 0);
5365         LASSERT(info->oti_w_locks == 0);
5366         LASSERT(info->oti_txns    == 0);
5367 }
5368
5369 /* type constructor/destructor: osd_type_init, osd_type_fini */
5370 LU_TYPE_INIT_FINI(osd, &osd_key);
5371
5372 struct lu_context_key osd_key = {
5373         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
5374         .lct_init = osd_key_init,
5375         .lct_fini = osd_key_fini,
5376         .lct_exit = osd_key_exit
5377 };
5378
5379
5380 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
5381                            const char *name, struct lu_device *next)
5382 {
5383         struct osd_device *osd = osd_dev(d);
5384
5385         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
5386             >= sizeof(osd->od_svname))
5387                 return -E2BIG;
5388         return osd_procfs_init(osd, name);
5389 }
5390
5391 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
5392 {
5393         ENTRY;
5394
5395         /* shutdown quota slave instance associated with the device */
5396         if (o->od_quota_slave != NULL) {
5397                 qsd_fini(env, o->od_quota_slave);
5398                 o->od_quota_slave = NULL;
5399         }
5400
5401         RETURN(0);
5402 }
5403
5404 static void osd_umount(const struct lu_env *env, struct osd_device *o)
5405 {
5406         ENTRY;
5407
5408         if (o->od_mnt != NULL) {
5409                 shrink_dcache_sb(osd_sb(o));
5410                 osd_sync(env, &o->od_dt_dev);
5411
5412                 mntput(o->od_mnt);
5413                 o->od_mnt = NULL;
5414         }
5415
5416         EXIT;
5417 }
5418
5419 static int osd_mount(const struct lu_env *env,
5420                      struct osd_device *o, struct lustre_cfg *cfg)
5421 {
5422         const char              *name  = lustre_cfg_string(cfg, 0);
5423         const char              *dev  = lustre_cfg_string(cfg, 1);
5424         const char              *opts;
5425         unsigned long            page, s_flags, lmd_flags = 0;
5426         struct page             *__page;
5427         struct file_system_type *type;
5428         char                    *options = NULL;
5429         char                    *str;
5430         struct osd_thread_info  *info = osd_oti_get(env);
5431         struct lu_fid           *fid = &info->oti_fid;
5432         struct inode            *inode;
5433         int                      rc = 0;
5434         ENTRY;
5435
5436         if (o->od_mnt != NULL)
5437                 RETURN(0);
5438
5439         if (strlen(dev) >= sizeof(o->od_mntdev))
5440                 RETURN(-E2BIG);
5441         strcpy(o->od_mntdev, dev);
5442
5443         OBD_PAGE_ALLOC(__page, GFP_IOFS);
5444         if (__page == NULL)
5445                 GOTO(out, rc = -ENOMEM);
5446
5447         str = lustre_cfg_string(cfg, 2);
5448         s_flags = simple_strtoul(str, NULL, 0);
5449         str = strstr(str, ":");
5450         if (str)
5451                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
5452         opts = lustre_cfg_string(cfg, 3);
5453         page = (unsigned long)page_address(__page);
5454         options = (char *)page;
5455         *options = '\0';
5456         if (opts == NULL)
5457                 strcat(options, "user_xattr,acl");
5458         else
5459                 strcat(options, opts);
5460
5461         /* Glom up mount options */
5462         if (*options != '\0')
5463                 strcat(options, ",");
5464         strlcat(options, "no_mbcache", PAGE_CACHE_SIZE);
5465
5466         type = get_fs_type("ldiskfs");
5467         if (!type) {
5468                 CERROR("%s: cannot find ldiskfs module\n", name);
5469                 GOTO(out, rc = -ENODEV);
5470         }
5471
5472         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
5473         module_put(type->owner);
5474
5475         if (IS_ERR(o->od_mnt)) {
5476                 rc = PTR_ERR(o->od_mnt);
5477                 o->od_mnt = NULL;
5478                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
5479                 GOTO(out, rc);
5480         }
5481
5482 #ifdef HAVE_DEV_SET_RDONLY
5483         if (dev_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
5484                 CERROR("%s: underlying device %s is marked as read-only. "
5485                        "Setup failed\n", name, dev);
5486                 GOTO(out_mnt, rc = -EROFS);
5487         }
5488 #endif
5489
5490         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
5491             LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
5492                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
5493                 GOTO(out_mnt, rc = -EINVAL);
5494         }
5495
5496         inode = osd_sb(o)->s_root->d_inode;
5497         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NO_OI);
5498         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
5499         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
5500         if (rc != 0) {
5501                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
5502                 GOTO(out_mnt, rc);
5503         }
5504
5505         if (lmd_flags & LMD_FLG_NOSCRUB)
5506                 o->od_noscrub = 1;
5507
5508         GOTO(out, rc = 0);
5509
5510 out_mnt:
5511         mntput(o->od_mnt);
5512         o->od_mnt = NULL;
5513
5514 out:
5515         if (__page)
5516                 OBD_PAGE_FREE(__page);
5517
5518         return rc;
5519 }
5520
5521 static struct lu_device *osd_device_fini(const struct lu_env *env,
5522                                          struct lu_device *d)
5523 {
5524         struct osd_device *o = osd_dev(d);
5525         ENTRY;
5526
5527         osd_procfs_fini(o);
5528         osd_shutdown(env, o);
5529         osd_scrub_cleanup(env, o);
5530         osd_obj_map_fini(o);
5531         osd_umount(env, o);
5532
5533         RETURN(NULL);
5534 }
5535
5536 static int osd_device_init0(const struct lu_env *env,
5537                             struct osd_device *o,
5538                             struct lustre_cfg *cfg)
5539 {
5540         struct lu_device        *l = osd2lu_dev(o);
5541         struct osd_thread_info *info;
5542         int                     rc;
5543         int                     cplen = 0;
5544
5545         /* if the module was re-loaded, env can loose its keys */
5546         rc = lu_env_refill((struct lu_env *) env);
5547         if (rc)
5548                 GOTO(out, rc);
5549         info = osd_oti_get(env);
5550         LASSERT(info);
5551
5552         l->ld_ops = &osd_lu_ops;
5553         o->od_dt_dev.dd_ops = &osd_dt_ops;
5554
5555         spin_lock_init(&o->od_osfs_lock);
5556         mutex_init(&o->od_otable_mutex);
5557         o->od_osfs_age = cfs_time_shift_64(-1000);
5558
5559         o->od_capa_hash = init_capa_hash();
5560         if (o->od_capa_hash == NULL)
5561                 GOTO(out, rc = -ENOMEM);
5562
5563         o->od_read_cache = 1;
5564         o->od_writethrough_cache = 1;
5565         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
5566
5567         rc = osd_mount(env, o, cfg);
5568         if (rc)
5569                 GOTO(out_capa, rc);
5570
5571         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
5572                         sizeof(o->od_svname));
5573         if (cplen >= sizeof(o->od_svname)) {
5574                 rc = -E2BIG;
5575                 GOTO(out_mnt, rc);
5576         }
5577
5578         if (server_name_is_ost(o->od_svname))
5579                 o->od_is_ost = 1;
5580
5581         rc = osd_obj_map_init(env, o);
5582         if (rc != 0)
5583                 GOTO(out_mnt, rc);
5584
5585         rc = lu_site_init(&o->od_site, l);
5586         if (rc != 0)
5587                 GOTO(out_compat, rc);
5588         o->od_site.ls_bottom_dev = l;
5589
5590         rc = lu_site_init_finish(&o->od_site);
5591         if (rc != 0)
5592                 GOTO(out_site, rc);
5593
5594         /* self-repair LMA by default */
5595         o->od_lma_self_repair = 1;
5596
5597         CFS_INIT_LIST_HEAD(&o->od_ios_list);
5598         /* setup scrub, including OI files initialization */
5599         rc = osd_scrub_setup(env, o);
5600         if (rc < 0)
5601                 GOTO(out_site, rc);
5602
5603         rc = osd_procfs_init(o, o->od_svname);
5604         if (rc != 0) {
5605                 CERROR("%s: can't initialize procfs: rc = %d\n",
5606                        o->od_svname, rc);
5607                 GOTO(out_scrub, rc);
5608         }
5609
5610         LASSERT(l->ld_site->ls_linkage.next && l->ld_site->ls_linkage.prev);
5611
5612         /* initialize quota slave instance */
5613         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
5614                                      o->od_proc_entry);
5615         if (IS_ERR(o->od_quota_slave)) {
5616                 rc = PTR_ERR(o->od_quota_slave);
5617                 o->od_quota_slave = NULL;
5618                 GOTO(out_procfs, rc);
5619         }
5620
5621         RETURN(0);
5622
5623 out_procfs:
5624         osd_procfs_fini(o);
5625 out_scrub:
5626         osd_scrub_cleanup(env, o);
5627 out_site:
5628         lu_site_fini(&o->od_site);
5629 out_compat:
5630         osd_obj_map_fini(o);
5631 out_mnt:
5632         osd_umount(env, o);
5633 out_capa:
5634         cleanup_capa_hash(o->od_capa_hash);
5635 out:
5636         return rc;
5637 }
5638
5639 static struct lu_device *osd_device_alloc(const struct lu_env *env,
5640                                           struct lu_device_type *t,
5641                                           struct lustre_cfg *cfg)
5642 {
5643         struct osd_device *o;
5644         int                rc;
5645
5646         OBD_ALLOC_PTR(o);
5647         if (o == NULL)
5648                 return ERR_PTR(-ENOMEM);
5649
5650         rc = dt_device_init(&o->od_dt_dev, t);
5651         if (rc == 0) {
5652                 /* Because the ctx might be revived in dt_device_init,
5653                  * refill the env here */
5654                 lu_env_refill((struct lu_env *)env);
5655                 rc = osd_device_init0(env, o, cfg);
5656                 if (rc)
5657                         dt_device_fini(&o->od_dt_dev);
5658         }
5659
5660         if (unlikely(rc != 0))
5661                 OBD_FREE_PTR(o);
5662
5663         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
5664 }
5665
5666 static struct lu_device *osd_device_free(const struct lu_env *env,
5667                                          struct lu_device *d)
5668 {
5669         struct osd_device *o = osd_dev(d);
5670         ENTRY;
5671
5672         cleanup_capa_hash(o->od_capa_hash);
5673         /* XXX: make osd top device in order to release reference */
5674         d->ld_site->ls_top_dev = d;
5675         lu_site_purge(env, d->ld_site, -1);
5676         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
5677                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
5678                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
5679         }
5680         lu_site_fini(&o->od_site);
5681         dt_device_fini(&o->od_dt_dev);
5682         OBD_FREE_PTR(o);
5683         RETURN(NULL);
5684 }
5685
5686 static int osd_process_config(const struct lu_env *env,
5687                               struct lu_device *d, struct lustre_cfg *cfg)
5688 {
5689         struct osd_device *o = osd_dev(d);
5690         int err;
5691         ENTRY;
5692
5693         switch(cfg->lcfg_command) {
5694         case LCFG_SETUP:
5695                 err = osd_mount(env, o, cfg);
5696                 break;
5697         case LCFG_CLEANUP:
5698                 lu_dev_del_linkage(d->ld_site, d);
5699                 err = osd_shutdown(env, o);
5700                 break;
5701         default:
5702                 err = -ENOSYS;
5703         }
5704
5705         RETURN(err);
5706 }
5707
5708 static int osd_recovery_complete(const struct lu_env *env,
5709                                  struct lu_device *d)
5710 {
5711         struct osd_device       *osd = osd_dev(d);
5712         int                      rc = 0;
5713         ENTRY;
5714
5715         if (osd->od_quota_slave == NULL)
5716                 RETURN(0);
5717
5718         /* start qsd instance on recovery completion, this notifies the quota
5719          * slave code that we are about to process new requests now */
5720         rc = qsd_start(env, osd->od_quota_slave);
5721         RETURN(rc);
5722 }
5723
5724 /*
5725  * we use exports to track all osd users
5726  */
5727 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
5728                            struct obd_device *obd, struct obd_uuid *cluuid,
5729                            struct obd_connect_data *data, void *localdata)
5730 {
5731         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
5732         struct lustre_handle  conn;
5733         int                   rc;
5734         ENTRY;
5735
5736         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
5737
5738         rc = class_connect(&conn, obd, cluuid);
5739         if (rc)
5740                 RETURN(rc);
5741
5742         *exp = class_conn2export(&conn);
5743
5744         spin_lock(&osd->od_osfs_lock);
5745         osd->od_connects++;
5746         spin_unlock(&osd->od_osfs_lock);
5747
5748         RETURN(0);
5749 }
5750
5751 /*
5752  * once last export (we don't count self-export) disappeared
5753  * osd can be released
5754  */
5755 static int osd_obd_disconnect(struct obd_export *exp)
5756 {
5757         struct obd_device *obd = exp->exp_obd;
5758         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
5759         int                rc, release = 0;
5760         ENTRY;
5761
5762         /* Only disconnect the underlying layers on the final disconnect. */
5763         spin_lock(&osd->od_osfs_lock);
5764         osd->od_connects--;
5765         if (osd->od_connects == 0)
5766                 release = 1;
5767         spin_unlock(&osd->od_osfs_lock);
5768
5769         rc = class_disconnect(exp); /* bz 9811 */
5770
5771         if (rc == 0 && release)
5772                 class_manual_cleanup(obd);
5773         RETURN(rc);
5774 }
5775
5776 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
5777                        struct lu_device *dev)
5778 {
5779         struct osd_device *osd = osd_dev(dev);
5780         int                result = 0;
5781         ENTRY;
5782
5783         if (osd->od_quota_slave != NULL)
5784                 /* set up quota slave objects */
5785                 result = qsd_prepare(env, osd->od_quota_slave);
5786
5787         RETURN(result);
5788 }
5789
5790 static const struct lu_object_operations osd_lu_obj_ops = {
5791         .loo_object_init      = osd_object_init,
5792         .loo_object_delete    = osd_object_delete,
5793         .loo_object_release   = osd_object_release,
5794         .loo_object_free      = osd_object_free,
5795         .loo_object_print     = osd_object_print,
5796         .loo_object_invariant = osd_object_invariant
5797 };
5798
5799 const struct lu_device_operations osd_lu_ops = {
5800         .ldo_object_alloc      = osd_object_alloc,
5801         .ldo_process_config    = osd_process_config,
5802         .ldo_recovery_complete = osd_recovery_complete,
5803         .ldo_prepare           = osd_prepare,
5804 };
5805
5806 static const struct lu_device_type_operations osd_device_type_ops = {
5807         .ldto_init = osd_type_init,
5808         .ldto_fini = osd_type_fini,
5809
5810         .ldto_start = osd_type_start,
5811         .ldto_stop  = osd_type_stop,
5812
5813         .ldto_device_alloc = osd_device_alloc,
5814         .ldto_device_free  = osd_device_free,
5815
5816         .ldto_device_init    = osd_device_init,
5817         .ldto_device_fini    = osd_device_fini
5818 };
5819
5820 struct lu_device_type osd_device_type = {
5821         .ldt_tags     = LU_DEVICE_DT,
5822         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
5823         .ldt_ops      = &osd_device_type_ops,
5824         .ldt_ctx_tags = LCT_LOCAL,
5825 };
5826
5827 /*
5828  * lprocfs legacy support.
5829  */
5830 static struct obd_ops osd_obd_device_ops = {
5831         .o_owner = THIS_MODULE,
5832         .o_connect      = osd_obd_connect,
5833         .o_disconnect   = osd_obd_disconnect
5834 };
5835
5836 static int __init osd_mod_init(void)
5837 {
5838         struct lprocfs_static_vars lvars;
5839         int rc;
5840
5841         osd_oi_mod_init();
5842         lprocfs_osd_init_vars(&lvars);
5843
5844         rc = lu_kmem_init(ldiskfs_caches);
5845         if (rc)
5846                 return rc;
5847
5848         rc = class_register_type(&osd_obd_device_ops, NULL, NULL,
5849 #ifndef HAVE_ONLY_PROCFS_SEQ
5850                                 lvars.module_vars,
5851 #endif
5852                                 LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
5853         if (rc)
5854                 lu_kmem_fini(ldiskfs_caches);
5855         return rc;
5856 }
5857
5858 static void __exit osd_mod_exit(void)
5859 {
5860         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
5861         lu_kmem_fini(ldiskfs_caches);
5862 }
5863
5864 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
5865 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
5866 MODULE_LICENSE("GPL");
5867
5868 cfs_module(osd, "0.1.0", osd_mod_init, osd_mod_exit);