Whamcloud - gitweb
LU-9704 grant: ignore grant info on read resend
[fs/lustre-release.git] / lustre / ofd / ofd_dev.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/ofd/ofd_dev.c
32  *
33  * This file contains OSD API methods for OBD Filter Device (OFD),
34  * request handlers and supplemental functions to set OFD up and clean it up.
35  *
36  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
37  * Author: Mike Pershin <mike.pershin@intel.com>
38  * Author: Johann Lombardi <johann.lombardi@intel.com>
39  */
40 /*
41  * The OBD Filter Device (OFD) module belongs to the Object Storage
42  * Server stack and connects the RPC oriented Unified Target (TGT)
43  * layer (see lustre/include/lu_target.h) to the storage oriented OSD
44  * layer (see Documentation/osd-api.txt).
45  *
46  *     TGT
47  *      |      DT and OBD APIs
48  *     OFD
49  *      |      DT API
50  *     OSD
51  *
52  * OFD implements the LU and OBD device APIs and is responsible for:
53  *
54  * - Handling client requests (create, destroy, bulk IO, setattr,
55  *   get_info, set_info, statfs) for the objects belonging to the OST
56  *   (together with TGT).
57  *
58  * - Providing grant space management which allows clients to reserve
59  *   disk space for data writeback. OFD tracks grants on global and
60  *   per client levels.
61  *
62  * - Handling object precreation requests from MDTs.
63  *
64  * - Operating the LDLM service that allows clients to maintain object
65  *   data cache coherence.
66  */
67
68 #define DEBUG_SUBSYSTEM S_FILTER
69
70 #include <obd_class.h>
71 #include <obd_cksum.h>
72 #include <uapi/linux/lustre/lustre_param.h>
73 #include <lustre_fid.h>
74 #include <lustre_lfsck.h>
75 #include <lustre_dlm.h>
76 #include <lustre_quota.h>
77 #include <lustre_nodemap.h>
78 #include <lustre_log.h>
79 #include <linux/falloc.h>
80
81 #include "ofd_internal.h"
82
83 /* Slab for OFD object allocation */
84 static struct kmem_cache *ofd_object_kmem;
85 static struct lu_kmem_descr ofd_caches[] = {
86         {
87                 .ckd_cache = &ofd_object_kmem,
88                 .ckd_name  = "ofd_obj",
89                 .ckd_size  = sizeof(struct ofd_object)
90         },
91         {
92                 .ckd_cache = NULL
93         }
94 };
95
96 /**
97  * Connect OFD to the next device in the stack.
98  *
99  * This function is used for device stack configuration and links OFD
100  * device with bottom OSD device.
101  *
102  * \param[in]  env      execution environment
103  * \param[in]  m        OFD device
104  * \param[in]  next     name of next device in the stack
105  * \param[out] exp      export to return
106  *
107  * \retval              0 and export in \a exp if successful
108  * \retval              negative value on error
109  */
110 static int ofd_connect_to_next(const struct lu_env *env, struct ofd_device *m,
111                                const char *next, struct obd_export **exp)
112 {
113         struct obd_connect_data *data = NULL;
114         struct obd_device       *obd;
115         int                      rc;
116         ENTRY;
117
118         OBD_ALLOC_PTR(data);
119         if (data == NULL)
120                 GOTO(out, rc = -ENOMEM);
121
122         obd = class_name2obd(next);
123         if (obd == NULL) {
124                 CERROR("%s: can't locate next device: %s\n",
125                        ofd_name(m), next);
126                 GOTO(out, rc = -ENOTCONN);
127         }
128
129         data->ocd_connect_flags = OBD_CONNECT_VERSION;
130         data->ocd_version = LUSTRE_VERSION_CODE;
131
132         rc = obd_connect(NULL, exp, obd, &obd->obd_uuid, data, NULL);
133         if (rc) {
134                 CERROR("%s: cannot connect to next dev %s: rc = %d\n",
135                        ofd_name(m), next, rc);
136                 GOTO(out, rc);
137         }
138
139         m->ofd_dt_dev.dd_lu_dev.ld_site =
140                 m->ofd_osd_exp->exp_obd->obd_lu_dev->ld_site;
141         LASSERT(m->ofd_dt_dev.dd_lu_dev.ld_site);
142         m->ofd_osd = lu2dt_dev(m->ofd_osd_exp->exp_obd->obd_lu_dev);
143         m->ofd_dt_dev.dd_lu_dev.ld_site->ls_top_dev = &m->ofd_dt_dev.dd_lu_dev;
144
145 out:
146         if (data)
147                 OBD_FREE_PTR(data);
148         RETURN(rc);
149 }
150
151 /**
152  * Initialize stack of devices.
153  *
154  * This function initializes OFD-OSD device stack to serve OST requests
155  *
156  * \param[in] env       execution environment
157  * \param[in] m         OFD device
158  * \param[in] cfg       Lustre config for this server
159  *
160  * \retval              0 if successful
161  * \retval              negative value on error
162  */
163 static int ofd_stack_init(const struct lu_env *env,
164                           struct ofd_device *m, struct lustre_cfg *cfg,
165                           u32 *lmd_flags)
166 {
167         const char              *dev = lustre_cfg_string(cfg, 0);
168         struct lu_device        *d;
169         struct ofd_thread_info  *info = ofd_info(env);
170         struct lustre_mount_info *lmi;
171         struct lustre_mount_data *lmd;
172         int                      rc;
173         char                    *osdname;
174
175         ENTRY;
176
177         lmi = server_get_mount(dev);
178         if (lmi == NULL) {
179                 CERROR("Cannot get mount info for %s!\n", dev);
180                 RETURN(-ENODEV);
181         }
182
183         lmd = s2lsi(lmi->lmi_sb)->lsi_lmd;
184         if (lmd) {
185                 if (lmd->lmd_flags & LMD_FLG_SKIP_LFSCK)
186                         m->ofd_skip_lfsck = 1;
187                 if (lmd->lmd_flags & LMD_FLG_NO_PRECREATE)
188                         m->ofd_no_precreate = 1;
189                 *lmd_flags = lmd->lmd_flags;
190         }
191
192         /* find bottom osd */
193         OBD_ALLOC(osdname, MTI_NAME_MAXLEN);
194         if (osdname == NULL)
195                 RETURN(-ENOMEM);
196
197         snprintf(osdname, MTI_NAME_MAXLEN, "%s-osd", dev);
198         rc = ofd_connect_to_next(env, m, osdname, &m->ofd_osd_exp);
199         OBD_FREE(osdname, MTI_NAME_MAXLEN);
200         if (rc)
201                 RETURN(rc);
202
203         d = m->ofd_osd_exp->exp_obd->obd_lu_dev;
204         LASSERT(d);
205         m->ofd_osd = lu2dt_dev(d);
206
207         snprintf(info->fti_u.name, sizeof(info->fti_u.name),
208                  "%s-osd", lustre_cfg_string(cfg, 0));
209
210         RETURN(rc);
211 }
212
213 /**
214  * Finalize the device stack OFD-OSD.
215  *
216  * This function cleans OFD-OSD device stack and
217  * disconnects OFD from the OSD.
218  *
219  * \param[in] env       execution environment
220  * \param[in] m         OFD device
221  * \param[in] top       top device of stack
222  *
223  * \retval              0 if successful
224  * \retval              negative value on error
225  */
226 static void ofd_stack_fini(const struct lu_env *env, struct ofd_device *m,
227                            struct lu_device *top)
228 {
229         struct obd_device       *obd = ofd_obd(m);
230         struct lustre_cfg_bufs   bufs;
231         struct lustre_cfg       *lcfg;
232         char                     flags[3] = "";
233
234         ENTRY;
235
236         lu_site_purge(env, top->ld_site, ~0);
237         /* process cleanup, pass mdt obd name to get obd umount flags */
238         lustre_cfg_bufs_reset(&bufs, obd->obd_name);
239         if (obd->obd_force)
240                 strcat(flags, "F");
241         if (obd->obd_fail)
242                 strcat(flags, "A");
243         lustre_cfg_bufs_set_string(&bufs, 1, flags);
244         OBD_ALLOC(lcfg, lustre_cfg_len(bufs.lcfg_bufcount, bufs.lcfg_buflen));
245         if (!lcfg)
246                 RETURN_EXIT;
247         lustre_cfg_init(lcfg, LCFG_CLEANUP, &bufs);
248
249         LASSERT(top);
250         top->ld_ops->ldo_process_config(env, top, lcfg);
251         OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount, lcfg->lcfg_buflens));
252
253         if (m->ofd_los != NULL) {
254                 local_oid_storage_fini(env, m->ofd_los);
255                 m->ofd_los = NULL;
256         }
257
258         lu_site_purge(env, top->ld_site, ~0);
259         lu_site_print(env, top->ld_site, &top->ld_site->ls_obj_hash.nelems,
260                       D_OTHER, lu_cdebug_printer);
261         LASSERT(m->ofd_osd_exp);
262         obd_disconnect(m->ofd_osd_exp);
263
264         EXIT;
265 }
266
267 static void ofd_stack_pre_fini(const struct lu_env *env, struct ofd_device *m,
268                                struct lu_device *top)
269 {
270         struct lustre_cfg_bufs bufs;
271         struct lustre_cfg *lcfg;
272         ENTRY;
273
274         LASSERT(top);
275
276         lustre_cfg_bufs_reset(&bufs, ofd_name(m));
277         lustre_cfg_bufs_set_string(&bufs, 1, NULL);
278         OBD_ALLOC(lcfg, lustre_cfg_len(bufs.lcfg_bufcount, bufs.lcfg_buflen));
279         if (!lcfg) {
280                 CERROR("%s: failed to trigger LCFG_PRE_CLEANUP\n", ofd_name(m));
281         } else {
282                 lustre_cfg_init(lcfg, LCFG_PRE_CLEANUP, &bufs);
283                 top->ld_ops->ldo_process_config(env, top, lcfg);
284                 OBD_FREE(lcfg, lustre_cfg_len(lcfg->lcfg_bufcount,
285                                               lcfg->lcfg_buflens));
286         }
287
288         EXIT;
289 }
290
291 /* For interoperability, see mdt_interop_param[]. */
292 static struct cfg_interop_param ofd_interop_param[] = {
293         { "ost.quota_type",     NULL },
294         { NULL }
295 };
296
297 /**
298  * Check if parameters are symlinks to the OSD.
299  *
300  * Some parameters were moved from ofd to osd and only their
301  * symlinks were kept in ofd by LU-3106. They are:
302  * -writehthrough_cache_enable
303  * -readcache_max_filesize
304  * -read_cache_enable
305  * -brw_stats
306  *
307  * Since they are not included by the static lprocfs var list, a pre-check
308  * is added for them to avoid "unknown param" errors. If they are matched
309  * in this check, they will be passed to the OSD directly.
310  *
311  * \param[in] param     parameters to check
312  *
313  * \retval              true if param is symlink to OSD param
314  *                      false otherwise
315  */
316 static bool match_symlink_param(char *param)
317 {
318         char *sval;
319         int paramlen;
320
321         if (class_match_param(param, PARAM_OST, &param) == 0) {
322                 sval = strchr(param, '=');
323                 if (sval != NULL) {
324                         paramlen = sval - param;
325                         if (strncmp(param, "brw_stats", paramlen) == 0)
326                                 return true;
327                 }
328         }
329
330         return false;
331 }
332
333 /**
334  * Process various configuration parameters.
335  *
336  * This function is used by MGS to process specific configurations and
337  * pass them through to the next device in server stack, i.e. the OSD.
338  *
339  * \param[in] env       execution environment
340  * \param[in] d         LU device of OFD
341  * \param[in] cfg       parameters to process
342  *
343  * \retval              0 if successful
344  * \retval              negative value on error
345  */
346 static int ofd_process_config(const struct lu_env *env, struct lu_device *d,
347                               struct lustre_cfg *cfg)
348 {
349         struct ofd_device       *m = ofd_dev(d);
350         struct dt_device        *dt_next = m->ofd_osd;
351         struct lu_device        *next = &dt_next->dd_lu_dev;
352         int                      rc;
353
354         ENTRY;
355
356         switch (cfg->lcfg_command) {
357         case LCFG_PARAM: {
358                 /* For interoperability */
359                 struct cfg_interop_param *ptr = NULL;
360                 struct lustre_cfg *old_cfg = NULL;
361                 char *param = NULL;
362                 ssize_t count;
363
364                 param = lustre_cfg_string(cfg, 1);
365                 if (param == NULL) {
366                         CERROR("param is empty\n");
367                         rc = -EINVAL;
368                         break;
369                 }
370
371                 ptr = class_find_old_param(param, ofd_interop_param);
372                 if (ptr != NULL) {
373                         if (ptr->new_param == NULL) {
374                                 rc = 0;
375                                 CWARN("For interoperability, skip this %s."
376                                       " It is obsolete.\n", ptr->old_param);
377                                 break;
378                         }
379
380                         CWARN("Found old param %s, changed it to %s.\n",
381                               ptr->old_param, ptr->new_param);
382
383                         old_cfg = cfg;
384                         cfg = lustre_cfg_rename(old_cfg, ptr->new_param);
385                         if (IS_ERR(cfg)) {
386                                 rc = PTR_ERR(cfg);
387                                 break;
388                         }
389                 }
390
391                 if (match_symlink_param(param)) {
392                         rc = next->ld_ops->ldo_process_config(env, next, cfg);
393                         break;
394                 }
395
396                 count = class_modify_config(cfg, PARAM_OST,
397                                             &d->ld_obd->obd_kset.kobj);
398                 if (count > 0) {
399                         rc = 0;
400                         break;
401                 }
402                 CDEBUG(D_CONFIG, "pass param %s down the stack.\n",
403                        param);
404                 /* we don't understand; pass it on */
405                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
406                 break;
407         }
408         case LCFG_SPTLRPC_CONF: {
409                 rc = -ENOTSUPP;
410                 break;
411         }
412         default:
413                 /* others are passed further */
414                 rc = next->ld_ops->ldo_process_config(env, next, cfg);
415                 break;
416         }
417         RETURN(rc);
418 }
419
420 /**
421  * Implementation of lu_object_operations::loo_object_init for OFD
422  *
423  * Allocate just the next object (OSD) in stack.
424  *
425  * \param[in] env       execution environment
426  * \param[in] o         lu_object of OFD object
427  * \param[in] conf      additional configuration parameters, not used here
428  *
429  * \retval              0 if successful
430  * \retval              negative value on error
431  */
432 static int ofd_object_init(const struct lu_env *env, struct lu_object *o,
433                            const struct lu_object_conf *conf)
434 {
435         struct ofd_device       *d = ofd_dev(o->lo_dev);
436         struct lu_device        *under;
437         struct lu_object        *below;
438         int                      rc = 0;
439
440         ENTRY;
441
442         CDEBUG(D_INFO, "object init, fid = "DFID"\n",
443                PFID(lu_object_fid(o)));
444
445         under = &d->ofd_osd->dd_lu_dev;
446         below = under->ld_ops->ldo_object_alloc(env, o->lo_header, under);
447         if (below != NULL)
448                 lu_object_add(o, below);
449         else
450                 rc = -ENOMEM;
451
452         RETURN(rc);
453 }
454
455 static void ofd_object_free_rcu(struct rcu_head *head)
456 {
457         struct ofd_object *of = container_of(head, struct ofd_object,
458                                              ofo_header.loh_rcu);
459
460         kmem_cache_free(ofd_object_kmem, of);
461 }
462
463 /**
464  * Implementation of lu_object_operations::loo_object_free.
465  *
466  * Finish OFD object lifecycle and free its memory.
467  *
468  * \param[in] env       execution environment
469  * \param[in] o         LU object of OFD object
470  */
471 static void ofd_object_free(const struct lu_env *env, struct lu_object *o)
472 {
473         struct ofd_object       *of = ofd_obj(o);
474         struct lu_object_header *h;
475
476         ENTRY;
477
478         h = o->lo_header;
479         CDEBUG(D_INFO, "object free, fid = "DFID"\n",
480                PFID(lu_object_fid(o)));
481
482         lu_object_fini(o);
483         lu_object_header_fini(h);
484         OBD_FREE_PRE(of, sizeof(*of), "slab-freed");
485         call_rcu(&of->ofo_header.loh_rcu, ofd_object_free_rcu);
486         EXIT;
487 }
488
489 /**
490  * Implementation of lu_object_operations::loo_object_print.
491  *
492  * Print OFD part of compound OFD-OSD object. See lu_object_print() and
493  * LU_OBJECT_DEBUG() for more details about the compound object printing.
494  *
495  * \param[in] env       execution environment
496  * \param[in] cookie    opaque data passed to the printer function
497  * \param[in] p         printer function to use
498  * \param[in] o         LU object of OFD object
499  *
500  * \retval              0 if successful
501  * \retval              negative value on error
502  */
503 static int ofd_object_print(const struct lu_env *env, void *cookie,
504                             lu_printer_t p, const struct lu_object *o)
505 {
506         return (*p)(env, cookie, LUSTRE_OST_NAME"-object@%p", o);
507 }
508
509 static const struct lu_object_operations ofd_obj_ops = {
510         .loo_object_init        = ofd_object_init,
511         .loo_object_free        = ofd_object_free,
512         .loo_object_print       = ofd_object_print
513 };
514
515 /**
516  * Implementation of lu_device_operations::lod_object_alloc.
517  *
518  * This function allocates OFD part of compound OFD-OSD object and
519  * initializes its header, because OFD is the top device in stack
520  *
521  * \param[in] env       execution environment
522  * \param[in] hdr       object header, NULL for OFD
523  * \param[in] d         lu_device
524  *
525  * \retval              allocated object if successful
526  * \retval              NULL value on failed allocation
527  */
528 static struct lu_object *ofd_object_alloc(const struct lu_env *env,
529                                           const struct lu_object_header *hdr,
530                                           struct lu_device *d)
531 {
532         struct ofd_object *of;
533
534         ENTRY;
535
536         OBD_SLAB_ALLOC_PTR_GFP(of, ofd_object_kmem, GFP_NOFS);
537         if (of != NULL) {
538                 struct lu_object        *o;
539                 struct lu_object_header *h;
540
541                 o = &of->ofo_obj.do_lu;
542                 h = &of->ofo_header;
543                 lu_object_header_init(h);
544                 lu_object_init(o, h, d);
545                 lu_object_add_top(h, o);
546                 o->lo_ops = &ofd_obj_ops;
547                 range_lock_tree_init(&of->ofo_write_tree);
548                 RETURN(o);
549         } else {
550                 RETURN(NULL);
551         }
552 }
553
554 /**
555  * Return the result of LFSCK run to the OFD.
556  *
557  * Notify OFD about result of LFSCK run. That may block the new object
558  * creation until problem is fixed by LFSCK.
559  *
560  * \param[in] env       execution environment
561  * \param[in] data      pointer to the OFD device
562  * \param[in] event     LFSCK event type
563  *
564  * \retval              0 if successful
565  * \retval              negative value on unknown event
566  */
567 static int ofd_lfsck_out_notify(const struct lu_env *env, void *data,
568                                 enum lfsck_events event)
569 {
570         struct ofd_device *ofd = data;
571         struct obd_device *obd = ofd_obd(ofd);
572
573         switch (event) {
574         case LE_LASTID_REBUILDING:
575                 CWARN("%s: Found crashed LAST_ID, deny creating new OST-object "
576                       "on the device until the LAST_ID rebuilt successfully.\n",
577                       obd->obd_name);
578                 down_write(&ofd->ofd_lastid_rwsem);
579                 ofd->ofd_lastid_rebuilding = 1;
580                 up_write(&ofd->ofd_lastid_rwsem);
581                 break;
582         case LE_LASTID_REBUILT: {
583                 down_write(&ofd->ofd_lastid_rwsem);
584                 ofd_seqs_free(env, ofd);
585                 ofd->ofd_lastid_rebuilding = 0;
586                 ofd->ofd_lastid_gen++;
587                 up_write(&ofd->ofd_lastid_rwsem);
588                 CWARN("%s: Rebuilt crashed LAST_ID files successfully.\n",
589                       obd->obd_name);
590                 break;
591         }
592         default:
593                 CERROR("%s: unknown lfsck event: rc = %d\n",
594                        ofd_name(ofd), event);
595                 return -EINVAL;
596         }
597
598         return 0;
599 }
600
601 /**
602  * Implementation of lu_device_operations::ldo_prepare.
603  *
604  * This method is called after layer has been initialized and before it starts
605  * serving user requests. In OFD it starts lfsk check routines and initializes
606  * recovery.
607  *
608  * \param[in] env       execution environment
609  * \param[in] pdev      higher device in stack, NULL for OFD
610  * \param[in] dev       lu_device of OFD device
611  *
612  * \retval              0 if successful
613  * \retval              negative value on error
614  */
615 static int ofd_prepare(const struct lu_env *env, struct lu_device *pdev,
616                        struct lu_device *dev)
617 {
618         struct ofd_thread_info          *info;
619         struct ofd_device               *ofd = ofd_dev(dev);
620         struct obd_device               *obd = ofd_obd(ofd);
621         struct lu_device                *next = &ofd->ofd_osd->dd_lu_dev;
622         int                              rc;
623
624         ENTRY;
625
626         info = ofd_info_init(env, NULL);
627         if (info == NULL)
628                 RETURN(-EFAULT);
629
630         /* initialize lower device */
631         rc = next->ld_ops->ldo_prepare(env, dev, next);
632         if (rc != 0)
633                 RETURN(rc);
634
635         rc = lfsck_register(env, ofd->ofd_osd, ofd->ofd_osd, obd,
636                             ofd_lfsck_out_notify, ofd, false);
637         if (rc != 0) {
638                 CERROR("%s: failed to initialize lfsck: rc = %d\n",
639                        obd->obd_name, rc);
640                 RETURN(rc);
641         }
642
643         rc = lfsck_register_namespace(env, ofd->ofd_osd, ofd->ofd_namespace);
644         /* The LFSCK instance is registered just now, so it must be there when
645          * register the namespace to such instance. */
646         LASSERTF(rc == 0, "register namespace failed: rc = %d\n", rc);
647
648         target_recovery_init(&ofd->ofd_lut, tgt_request_handle);
649         OBD_FAIL_TIMEOUT_ORSET(OBD_FAIL_OST_PREPARE_DELAY, OBD_FAIL_ONCE,
650                                (OBD_TIMEOUT_DEFAULT + 1) / 4);
651         LASSERT(obd->obd_no_conn);
652         spin_lock(&obd->obd_dev_lock);
653         obd->obd_no_conn = 0;
654         spin_unlock(&obd->obd_dev_lock);
655
656         if (obd->obd_recovering == 0)
657                 ofd_postrecov(env, ofd);
658
659         RETURN(rc);
660 }
661
662 /**
663  * Implementation of lu_device_operations::ldo_recovery_complete.
664  *
665  * This method notifies all layers about 'recovery complete' event. That means
666  * device is in full state and consistent. An OFD calculates available grant
667  * space upon this event.
668  *
669  * \param[in] env       execution environment
670  * \param[in] dev       lu_device of OFD device
671  *
672  * \retval              0 if successful
673  * \retval              negative value on error
674  */
675 static int ofd_recovery_complete(const struct lu_env *env,
676                                  struct lu_device *dev)
677 {
678         struct ofd_thread_info  *oti = ofd_info(env);
679         struct ofd_device       *ofd = ofd_dev(dev);
680         struct lu_device        *next = &ofd->ofd_osd->dd_lu_dev;
681         int                      rc = 0;
682
683         ENTRY;
684
685         /*
686          * Grant space for object precreation on the self export.
687          * The initial reserved space (i.e. 10MB for zfs and 280KB for ldiskfs)
688          * is enough to create 10k objects. More space is then acquired for
689          * precreation in tgt_grant_create().
690          */
691         memset(&oti->fti_ocd, 0, sizeof(oti->fti_ocd));
692         oti->fti_ocd.ocd_grant = OST_MAX_PRECREATE / 2;
693         oti->fti_ocd.ocd_grant *= ofd->ofd_lut.lut_dt_conf.ddp_inodespace;
694         oti->fti_ocd.ocd_connect_flags = OBD_CONNECT_GRANT |
695                                          OBD_CONNECT_GRANT_PARAM;
696         tgt_grant_connect(env, dev->ld_obd->obd_self_export, &oti->fti_ocd,
697                           true);
698         rc = next->ld_ops->ldo_recovery_complete(env, next);
699         RETURN(rc);
700 }
701
702 /**
703  * lu_device_operations matrix for OFD device.
704  */
705 static const struct lu_device_operations ofd_lu_ops = {
706         .ldo_object_alloc       = ofd_object_alloc,
707         .ldo_process_config     = ofd_process_config,
708         .ldo_recovery_complete  = ofd_recovery_complete,
709         .ldo_prepare            = ofd_prepare,
710 };
711
712 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
713 /**
714  * Expose OSD statistics to OFD layer.
715  *
716  * The osd interfaces to the backend file system exposes useful data
717  * such as brw_stats and read or write cache states. This same data
718  * needs to be exposed into the obdfilter (ofd) layer to maintain
719  * backwards compatibility. This function creates the symlinks in the
720  * proc layer to enable this.
721  *
722  * \param[in] ofd       OFD device
723  */
724 static void ofd_procfs_add_brw_stats_symlink(struct ofd_device *ofd)
725 {
726         struct obd_device *obd = ofd_obd(ofd);
727         struct obd_device *osd_obd = ofd->ofd_osd_exp->exp_obd;
728         struct kobj_type *osd_type;
729         int i;
730
731         osd_type = get_ktype(&ofd->ofd_osd->dd_kobj);
732         for (i = 0; osd_type->default_attrs[i]; i++) {
733                 if (strcmp(osd_type->default_attrs[i]->name,
734                            "read_cache_enable") == 0) {
735                         ofd->ofd_read_cache_enable =
736                                 osd_type->default_attrs[i];
737                 }
738
739                 if (strcmp(osd_type->default_attrs[i]->name,
740                            "readcache_max_filesize") == 0) {
741                         ofd->ofd_read_cache_max_filesize =
742                                 osd_type->default_attrs[i];
743                 }
744
745                 if (strcmp(osd_type->default_attrs[i]->name,
746                            "writethrough_cache_enable") == 0) {
747                         ofd->ofd_write_cache_enable =
748                                 osd_type->default_attrs[i];
749                 }
750         }
751
752         if (obd->obd_proc_entry == NULL)
753                 return;
754
755         lprocfs_add_symlink("brw_stats", obd->obd_proc_entry,
756                             "../../%s/%s/brw_stats",
757                             osd_obd->obd_type->typ_name, obd->obd_name);
758 }
759 #endif
760
761 /**
762  * Cleanup all procfs entries in OFD.
763  *
764  * \param[in] ofd       OFD device
765  */
766 static void ofd_procfs_fini(struct ofd_device *ofd)
767 {
768         struct obd_device *obd = ofd_obd(ofd);
769
770         tgt_tunables_fini(&ofd->ofd_lut);
771         lprocfs_free_per_client_stats(obd);
772         lprocfs_obd_cleanup(obd);
773         lprocfs_free_obd_stats(obd);
774         lprocfs_job_stats_fini(obd);
775 }
776
777 /**
778  * Stop SEQ/FID server on OFD.
779  *
780  * \param[in] env       execution environment
781  * \param[in] ofd       OFD device
782  *
783  * \retval              0 if successful
784  * \retval              negative value on error
785  */
786 int ofd_fid_fini(const struct lu_env *env, struct ofd_device *ofd)
787 {
788         return seq_site_fini(env, &ofd->ofd_seq_site);
789 }
790
791 /**
792  * Start SEQ/FID server on OFD.
793  *
794  * The SEQ/FID server on OFD is needed to allocate FIDs for new objects.
795  * It also connects to the master server to get own FID sequence (SEQ) range
796  * to this particular OFD. Typically that happens when the OST is first
797  * formatted or in the rare case that it exhausts the local sequence range.
798  *
799  * The sequence range is allocated out to the MDTs for OST object allocations,
800  * and not directly to the clients.
801  *
802  * \param[in] env       execution environment
803  * \param[in] ofd       OFD device
804  *
805  * \retval              0 if successful
806  * \retval              negative value on error
807  */
808 int ofd_fid_init(const struct lu_env *env, struct ofd_device *ofd)
809 {
810         struct seq_server_site *ss = &ofd->ofd_seq_site;
811         struct lu_device *lu = &ofd->ofd_dt_dev.dd_lu_dev;
812         char *obd_name = ofd_name(ofd);
813         char *name = NULL;
814         int len = strlen(obd_name) + 7;
815         int rc = 0;
816
817         ss = &ofd->ofd_seq_site;
818         lu->ld_site->ld_seq_site = ss;
819         ss->ss_lu = lu->ld_site;
820         ss->ss_node_id = ofd->ofd_lut.lut_lsd.lsd_osd_index;
821
822         OBD_ALLOC(name, len);
823         if (name == NULL)
824                 return -ENOMEM;
825
826         OBD_ALLOC_PTR(ss->ss_server_seq);
827         if (ss->ss_server_seq == NULL)
828                 GOTO(out_name, rc = -ENOMEM);
829
830         rc = seq_server_init(env, ss->ss_server_seq, ofd->ofd_osd, obd_name,
831                              LUSTRE_SEQ_SERVER, ss);
832         if (rc) {
833                 CERROR("%s: seq server init error: rc = %d\n", obd_name, rc);
834                 GOTO(out_server, rc);
835         }
836         ss->ss_server_seq->lss_space.lsr_index = ss->ss_node_id;
837
838         OBD_ALLOC_PTR(ss->ss_client_seq);
839         if (ss->ss_client_seq == NULL)
840                 GOTO(out_server, rc = -ENOMEM);
841
842         snprintf(name, len, "%s-super", obd_name);
843         seq_client_init(ss->ss_client_seq, NULL, LUSTRE_SEQ_DATA,
844                         name, NULL);
845
846         rc = seq_server_set_cli(env, ss->ss_server_seq, ss->ss_client_seq);
847
848         if (rc) {
849                 seq_client_fini(ss->ss_client_seq);
850                 OBD_FREE_PTR(ss->ss_client_seq);
851                 ss->ss_client_seq = NULL;
852 out_server:
853                 seq_server_fini(ss->ss_server_seq, env);
854                 OBD_FREE_PTR(ss->ss_server_seq);
855                 ss->ss_server_seq = NULL;
856         }
857 out_name:
858         OBD_FREE(name, len);
859
860         return rc;
861 }
862
863 /**
864  * OFD request handler for OST_SET_INFO RPC.
865  *
866  * This is OFD-specific part of request handling
867  *
868  * \param[in] tsi       target session environment for this request
869  *
870  * \retval              0 if successful
871  * \retval              negative value on error
872  */
873 static int ofd_set_info_hdl(struct tgt_session_info *tsi)
874 {
875         struct ptlrpc_request   *req = tgt_ses_req(tsi);
876         struct ost_body         *body = NULL, *repbody;
877         void                    *key, *val = NULL;
878         int                      keylen, vallen, rc = 0;
879         bool                     is_grant_shrink;
880         ktime_t                  kstart = ktime_get();
881
882         ENTRY;
883
884         key = req_capsule_client_get(tsi->tsi_pill, &RMF_SETINFO_KEY);
885         if (key == NULL) {
886                 DEBUG_REQ(D_HA, req, "no set_info key");
887                 RETURN(err_serious(-EFAULT));
888         }
889         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_SETINFO_KEY,
890                                       RCL_CLIENT);
891
892         val = req_capsule_client_get(tsi->tsi_pill, &RMF_SETINFO_VAL);
893         if (val == NULL) {
894                 DEBUG_REQ(D_HA, req, "no set_info val");
895                 RETURN(err_serious(-EFAULT));
896         }
897         vallen = req_capsule_get_size(tsi->tsi_pill, &RMF_SETINFO_VAL,
898                                       RCL_CLIENT);
899
900         is_grant_shrink = KEY_IS(KEY_GRANT_SHRINK);
901         if (is_grant_shrink)
902                 /* In this case the value is actually an RMF_OST_BODY, so we
903                  * transmutate the type of this PTLRPC */
904                 req_capsule_extend(tsi->tsi_pill, &RQF_OST_SET_GRANT_INFO);
905
906         rc = req_capsule_server_pack(tsi->tsi_pill);
907         if (rc < 0)
908                 RETURN(rc);
909
910         if (is_grant_shrink) {
911                 body = req_capsule_client_get(tsi->tsi_pill, &RMF_OST_BODY);
912
913                 /*
914                  * Because we already sync grant info with client when
915                  * reconnect, grant info will be cleared for resent
916                  * req, otherwise, outdated grant count in the rpc
917                  * would de-sync grant counters
918                  */
919                 if (lustre_msg_get_flags(req->rq_reqmsg) &
920                     (MSG_RESENT | MSG_REPLAY)) {
921                         DEBUG_REQ(D_CACHE, req,
922                                   "clear resent/replay req grant info");
923                         body->oa.o_valid &= ~OBD_MD_FLGRANT;
924                 }
925
926                 repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_OST_BODY);
927                 *repbody = *body;
928
929                 /** handle grant shrink, similar to a read request */
930                 tgt_grant_prepare_read(tsi->tsi_env, tsi->tsi_exp,
931                                        &repbody->oa);
932         } else if (KEY_IS(KEY_EVICT_BY_NID)) {
933                 if (vallen > 0)
934                         obd_export_evict_by_nid(tsi->tsi_exp->exp_obd, val);
935                 rc = 0;
936         } else {
937                 CERROR("%s: Unsupported key %s\n",
938                        tgt_name(tsi->tsi_tgt), (char *)key);
939                 rc = -EOPNOTSUPP;
940         }
941         ofd_counter_incr(tsi->tsi_exp, LPROC_OFD_STATS_SET_INFO,
942                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
943
944         RETURN(rc);
945 }
946
947 /**
948  * Get FIEMAP (FIle Extent MAPping) for object with the given FID.
949  *
950  * This function returns a list of extents which describes how a file's
951  * blocks are laid out on the disk.
952  *
953  * \param[in] env       execution environment
954  * \param[in] ofd       OFD device
955  * \param[in] fid       FID of object
956  * \param[in] fiemap    fiemap structure to fill with data
957  *
958  * \retval              0 if \a fiemap is filled with data successfully
959  * \retval              negative value on error
960  */
961 int ofd_fiemap_get(const struct lu_env *env, struct ofd_device *ofd,
962                    struct lu_fid *fid, struct fiemap *fiemap)
963 {
964         struct ofd_object       *fo;
965         int                      rc;
966
967         fo = ofd_object_find(env, ofd, fid);
968         if (IS_ERR(fo)) {
969                 CERROR("%s: error finding object "DFID"\n",
970                        ofd_name(ofd), PFID(fid));
971                 return PTR_ERR(fo);
972         }
973
974         ofd_read_lock(env, fo);
975         if (ofd_object_exists(fo))
976                 rc = dt_fiemap_get(env, ofd_object_child(fo), fiemap);
977         else
978                 rc = -ENOENT;
979         ofd_read_unlock(env, fo);
980         ofd_object_put(env, fo);
981         return rc;
982 }
983
984
985 static int ofd_lock_unlock_region(const struct lu_env *env,
986                                   struct ldlm_namespace *ns,
987                                   struct ldlm_res_id *res_id,
988                                   unsigned long long begin,
989                                   unsigned long long end)
990 {
991         __u64                    flags = 0;
992         int                      rc;
993         struct lustre_handle     lh = { 0 };
994
995         LASSERT(begin <= end);
996
997         rc = tgt_extent_lock(env, ns, res_id, begin, end, &lh, LCK_PR, &flags);
998         if (rc != 0)
999                 return rc;
1000
1001         CDEBUG(D_OTHER, "ost lock [%llu,%llu], lh=%p\n", begin, end, &lh);
1002         tgt_data_unlock(&lh, LCK_PR);
1003
1004         return 0;
1005 }
1006
1007 /**
1008  * Lock the sparse areas of given resource.
1009  *
1010  * The locking of sparse areas will cause dirty data to be flushed back from
1011  * clients. This is used when getting the FIEMAP of an object to make sure
1012  * there is no unaccounted cached data on clients.
1013  *
1014  * This function goes through \a fiemap list of extents and locks only sparse
1015  * areas between extents.
1016  *
1017  * \param[in] ns        LDLM namespace
1018  * \param[in] res_id    resource ID
1019  * \param[in] fiemap    file extents mapping on disk
1020  * \param[in] locked    list head of regions list
1021  *
1022  * \retval              0 if successful
1023  * \retval              negative value on error
1024  */
1025 static int lock_zero_regions(const struct lu_env *env,
1026                              struct ldlm_namespace *ns,
1027                              struct ldlm_res_id *res_id,
1028                              struct fiemap *fiemap)
1029 {
1030         __u64 begin = fiemap->fm_start;
1031         unsigned int i;
1032         int rc = 0;
1033         struct fiemap_extent *fiemap_start = fiemap->fm_extents;
1034
1035         ENTRY;
1036
1037         CDEBUG(D_OTHER, "extents count %u\n", fiemap->fm_mapped_extents);
1038         for (i = 0; i < fiemap->fm_mapped_extents; i++) {
1039                 if (fiemap_start[i].fe_logical > begin) {
1040                         CDEBUG(D_OTHER, "ost lock [%llu,%llu]\n",
1041                                begin, fiemap_start[i].fe_logical);
1042                         rc = ofd_lock_unlock_region(env, ns, res_id, begin,
1043                                                     fiemap_start[i].fe_logical);
1044                         if (rc)
1045                                 RETURN(rc);
1046                 }
1047
1048                 begin = fiemap_start[i].fe_logical + fiemap_start[i].fe_length;
1049         }
1050
1051         if (begin < (fiemap->fm_start + fiemap->fm_length)) {
1052                 CDEBUG(D_OTHER, "ost lock [%llu,%llu]\n",
1053                        begin, fiemap->fm_start + fiemap->fm_length);
1054                 rc = ofd_lock_unlock_region(env, ns, res_id, begin,
1055                                 fiemap->fm_start + fiemap->fm_length);
1056         }
1057
1058         RETURN(rc);
1059 }
1060
1061
1062 /**
1063  * OFD request handler for OST_GET_INFO RPC.
1064  *
1065  * This is OFD-specific part of request handling. The OFD-specific keys are:
1066  * - KEY_LAST_ID (obsolete)
1067  * - KEY_FIEMAP
1068  * - KEY_LAST_FID
1069  *
1070  * This function reads needed data from storage and fills reply with it.
1071  *
1072  * Note: the KEY_LAST_ID is obsolete, replaced by KEY_LAST_FID on newer MDTs,
1073  * and is kept for compatibility.
1074  *
1075  * \param[in] tsi       target session environment for this request
1076  *
1077  * \retval              0 if successful
1078  * \retval              negative value on error
1079  */
1080 static int ofd_get_info_hdl(struct tgt_session_info *tsi)
1081 {
1082         struct obd_export               *exp = tsi->tsi_exp;
1083         struct ofd_device               *ofd = ofd_exp(exp);
1084         struct ofd_thread_info          *fti = tsi2ofd_info(tsi);
1085         void                            *key;
1086         int                              keylen;
1087         int                              replylen, rc = 0;
1088         ktime_t                          kstart = ktime_get();
1089
1090         ENTRY;
1091
1092         /* this common part for get_info rpc */
1093         key = req_capsule_client_get(tsi->tsi_pill, &RMF_GETINFO_KEY);
1094         if (key == NULL) {
1095                 DEBUG_REQ(D_HA, tgt_ses_req(tsi), "no get_info key");
1096                 RETURN(err_serious(-EPROTO));
1097         }
1098         keylen = req_capsule_get_size(tsi->tsi_pill, &RMF_GETINFO_KEY,
1099                                       RCL_CLIENT);
1100
1101         if (KEY_IS(KEY_LAST_ID)) {
1102                 u64             *last_id;
1103                 struct ofd_seq  *oseq;
1104
1105                 req_capsule_extend(tsi->tsi_pill, &RQF_OST_GET_INFO_LAST_ID);
1106                 rc = req_capsule_server_pack(tsi->tsi_pill);
1107                 if (rc)
1108                         RETURN(err_serious(rc));
1109
1110                 last_id = req_capsule_server_get(tsi->tsi_pill, &RMF_OBD_ID);
1111
1112                 oseq = ofd_seq_load(tsi->tsi_env, ofd,
1113                                     (u64)exp->exp_filter_data.fed_group);
1114                 if (IS_ERR(oseq))
1115                         rc = -EFAULT;
1116                 else
1117                         *last_id = ofd_seq_last_oid(oseq);
1118                 ofd_seq_put(tsi->tsi_env, oseq);
1119         } else if (KEY_IS(KEY_FIEMAP)) {
1120                 struct ll_fiemap_info_key       *fm_key;
1121                 struct fiemap                   *fiemap;
1122                 struct lu_fid                   *fid;
1123
1124                 req_capsule_extend(tsi->tsi_pill, &RQF_OST_GET_INFO_FIEMAP);
1125
1126                 fm_key = req_capsule_client_get(tsi->tsi_pill, &RMF_FIEMAP_KEY);
1127                 rc = tgt_validate_obdo(tsi, &fm_key->lfik_oa);
1128                 if (rc)
1129                         RETURN(err_serious(rc));
1130
1131                 fid = &fm_key->lfik_oa.o_oi.oi_fid;
1132
1133                 CDEBUG(D_INODE, "get FIEMAP of object "DFID"\n", PFID(fid));
1134
1135                 replylen = fiemap_count_to_size(
1136                                         fm_key->lfik_fiemap.fm_extent_count);
1137                 req_capsule_set_size(tsi->tsi_pill, &RMF_FIEMAP_VAL,
1138                                      RCL_SERVER, replylen);
1139
1140                 rc = req_capsule_server_pack(tsi->tsi_pill);
1141                 if (rc)
1142                         RETURN(err_serious(rc));
1143
1144                 fiemap = req_capsule_server_get(tsi->tsi_pill, &RMF_FIEMAP_VAL);
1145                 if (fiemap == NULL)
1146                         RETURN(-ENOMEM);
1147
1148                 *fiemap = fm_key->lfik_fiemap;
1149                 rc = ofd_fiemap_get(tsi->tsi_env, ofd, fid, fiemap);
1150
1151                 /* LU-3219: Lock the sparse areas to make sure dirty
1152                  * flushed back from client, then call fiemap again. */
1153                 if (fm_key->lfik_oa.o_valid & OBD_MD_FLFLAGS &&
1154                     fm_key->lfik_oa.o_flags & OBD_FL_SRVLOCK) {
1155                         ost_fid_build_resid(fid, &fti->fti_resid);
1156                         rc = lock_zero_regions(tsi->tsi_env, ofd->ofd_namespace,
1157                                                &fti->fti_resid, fiemap);
1158                         if (rc == 0)
1159                                 rc = ofd_fiemap_get(tsi->tsi_env, ofd, fid,
1160                                                     fiemap);
1161                 }
1162         } else if (KEY_IS(KEY_LAST_FID)) {
1163                 struct ofd_device       *ofd = ofd_exp(exp);
1164                 struct ofd_seq          *oseq;
1165                 struct lu_fid           *fid;
1166                 int                      rc;
1167
1168                 req_capsule_extend(tsi->tsi_pill, &RQF_OST_GET_INFO_LAST_FID);
1169                 rc = req_capsule_server_pack(tsi->tsi_pill);
1170                 if (rc)
1171                         RETURN(err_serious(rc));
1172
1173                 fid = req_capsule_client_get(tsi->tsi_pill, &RMF_FID);
1174                 if (fid == NULL)
1175                         RETURN(err_serious(-EPROTO));
1176
1177                 fid_le_to_cpu(&fti->fti_ostid.oi_fid, fid);
1178
1179                 fid = req_capsule_server_get(tsi->tsi_pill, &RMF_FID);
1180                 if (fid == NULL)
1181                         RETURN(-ENOMEM);
1182
1183                 oseq = ofd_seq_load(tsi->tsi_env, ofd,
1184                                     ostid_seq(&fti->fti_ostid));
1185                 if (IS_ERR(oseq))
1186                         RETURN(PTR_ERR(oseq));
1187
1188                 rc = ostid_to_fid(fid, &oseq->os_oi,
1189                                   ofd->ofd_lut.lut_lsd.lsd_osd_index);
1190                 if (rc != 0)
1191                         GOTO(out_put, rc);
1192
1193                 CDEBUG(D_HA, "%s: LAST FID is "DFID"\n", ofd_name(ofd),
1194                        PFID(fid));
1195 out_put:
1196                 ofd_seq_put(tsi->tsi_env, oseq);
1197         } else {
1198                 CERROR("%s: not supported key %s\n", tgt_name(tsi->tsi_tgt),
1199                        (char *)key);
1200                 rc = -EOPNOTSUPP;
1201         }
1202         ofd_counter_incr(tsi->tsi_exp, LPROC_OFD_STATS_GET_INFO,
1203                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
1204
1205         RETURN(rc);
1206 }
1207
1208 /**
1209  * OFD request handler for OST_GETATTR RPC.
1210  *
1211  * This is OFD-specific part of request handling. It finds the OFD object
1212  * by its FID, gets attributes from storage and packs result to the reply.
1213  *
1214  * \param[in] tsi       target session environment for this request
1215  *
1216  * \retval              0 if successful
1217  * \retval              negative value on error
1218  */
1219 static int ofd_getattr_hdl(struct tgt_session_info *tsi)
1220 {
1221         struct ofd_thread_info  *fti = tsi2ofd_info(tsi);
1222         struct ofd_device       *ofd = ofd_exp(tsi->tsi_exp);
1223         struct ost_body         *repbody;
1224         struct lustre_handle     lh = { 0 };
1225         struct ofd_object       *fo;
1226         __u64                    flags = 0;
1227         enum ldlm_mode           lock_mode = LCK_PR;
1228         ktime_t                  kstart = ktime_get();
1229         bool                     srvlock;
1230         int                      rc;
1231         ENTRY;
1232
1233         LASSERT(tsi->tsi_ost_body != NULL);
1234
1235         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_OST_BODY);
1236         if (repbody == NULL)
1237                 RETURN(-ENOMEM);
1238
1239         repbody->oa.o_oi = tsi->tsi_ost_body->oa.o_oi;
1240         repbody->oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
1241
1242         srvlock = tsi->tsi_ost_body->oa.o_valid & OBD_MD_FLFLAGS &&
1243                   tsi->tsi_ost_body->oa.o_flags & OBD_FL_SRVLOCK;
1244
1245         if (srvlock) {
1246                 if (unlikely(tsi->tsi_ost_body->oa.o_flags & OBD_FL_FLUSH))
1247                         lock_mode = LCK_PW;
1248
1249                 rc = tgt_extent_lock(tsi->tsi_env,
1250                                      tsi->tsi_tgt->lut_obd->obd_namespace,
1251                                      &tsi->tsi_resid, 0, OBD_OBJECT_EOF, &lh,
1252                                      lock_mode, &flags);
1253                 if (rc != 0)
1254                         RETURN(rc);
1255         }
1256
1257         fo = ofd_object_find_exists(tsi->tsi_env, ofd, &tsi->tsi_fid);
1258         if (IS_ERR(fo))
1259                 GOTO(out, rc = PTR_ERR(fo));
1260
1261         rc = ofd_attr_get(tsi->tsi_env, fo, &fti->fti_attr);
1262         if (rc == 0) {
1263                 __u64    curr_version;
1264
1265                 obdo_from_la(&repbody->oa, &fti->fti_attr,
1266                              OFD_VALID_FLAGS | LA_UID | LA_GID | LA_PROJID);
1267
1268                 /* Store object version in reply */
1269                 curr_version = dt_version_get(tsi->tsi_env,
1270                                               ofd_object_child(fo));
1271                 if ((__s64)curr_version != -EOPNOTSUPP) {
1272                         repbody->oa.o_valid |= OBD_MD_FLDATAVERSION;
1273                         repbody->oa.o_data_version = curr_version;
1274                 }
1275
1276                 if (fo->ofo_ff.ff_layout_version > 0) {
1277                         repbody->oa.o_valid |= OBD_MD_LAYOUT_VERSION;
1278                         repbody->oa.o_layout_version =
1279                              fo->ofo_ff.ff_layout_version + fo->ofo_ff.ff_range;
1280
1281                         CDEBUG(D_INODE, DFID": get layout version: %u\n",
1282                                PFID(&tsi->tsi_fid),
1283                                repbody->oa.o_layout_version);
1284                 }
1285         }
1286
1287         ofd_object_put(tsi->tsi_env, fo);
1288 out:
1289         if (srvlock)
1290                 tgt_data_unlock(&lh, lock_mode);
1291
1292         ofd_counter_incr(tsi->tsi_exp, LPROC_OFD_STATS_GETATTR,
1293                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
1294
1295         repbody->oa.o_valid |= OBD_MD_FLFLAGS;
1296         repbody->oa.o_flags = OBD_FL_FLUSH;
1297
1298         RETURN(rc);
1299 }
1300
1301 /**
1302  * OFD request handler for OST_SETATTR RPC.
1303  *
1304  * This is OFD-specific part of request handling. It finds the OFD object
1305  * by its FID, sets attributes from request and packs result to the reply.
1306  *
1307  * \param[in] tsi       target session environment for this request
1308  *
1309  * \retval              0 if successful
1310  * \retval              negative value on error
1311  */
1312 static int ofd_setattr_hdl(struct tgt_session_info *tsi)
1313 {
1314         struct ofd_thread_info  *fti = tsi2ofd_info(tsi);
1315         struct ofd_device       *ofd = ofd_exp(tsi->tsi_exp);
1316         struct ost_body         *body = tsi->tsi_ost_body;
1317         struct ost_body         *repbody;
1318         struct ldlm_resource    *res;
1319         struct ofd_object       *fo;
1320         ktime_t                  kstart = ktime_get();
1321         int                      rc = 0;
1322
1323         ENTRY;
1324
1325         LASSERT(body != NULL);
1326
1327         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_OST_BODY);
1328         if (repbody == NULL)
1329                 RETURN(-ENOMEM);
1330
1331         repbody->oa.o_oi = body->oa.o_oi;
1332         repbody->oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
1333
1334         /* This would be very bad - accidentally truncating a file when
1335          * changing the time or similar - bug 12203. */
1336         if (body->oa.o_valid & OBD_MD_FLSIZE &&
1337             body->oa.o_size != OBD_OBJECT_EOF) {
1338                 static char mdsinum[48];
1339
1340                 if (body->oa.o_valid & OBD_MD_FLFID)
1341                         snprintf(mdsinum, sizeof(mdsinum) - 1,
1342                                  "of parent "DFID, body->oa.o_parent_seq,
1343                                  body->oa.o_parent_oid, 0);
1344                 else
1345                         mdsinum[0] = '\0';
1346
1347                 CERROR("%s: setattr from %s is trying to truncate object "DFID
1348                        " %s\n", ofd_name(ofd), obd_export_nid2str(tsi->tsi_exp),
1349                        PFID(&tsi->tsi_fid), mdsinum);
1350                 RETURN(-EPERM);
1351         }
1352
1353         fo = ofd_object_find_exists(tsi->tsi_env, ofd, &tsi->tsi_fid);
1354         if (IS_ERR(fo))
1355                 GOTO(out, rc = PTR_ERR(fo));
1356
1357         la_from_obdo(&fti->fti_attr, &body->oa, body->oa.o_valid);
1358         fti->fti_attr.la_valid &= ~LA_TYPE;
1359
1360         /* setting objects attributes (including owner/group) */
1361         rc = ofd_attr_set(tsi->tsi_env, fo, &fti->fti_attr, &body->oa);
1362         if (rc != 0)
1363                 GOTO(out_put, rc);
1364
1365         obdo_from_la(&repbody->oa, &fti->fti_attr,
1366                      OFD_VALID_FLAGS | LA_UID | LA_GID | LA_PROJID);
1367
1368         ofd_counter_incr(tsi->tsi_exp, LPROC_OFD_STATS_SETATTR,
1369                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
1370         EXIT;
1371 out_put:
1372         ofd_object_put(tsi->tsi_env, fo);
1373 out:
1374         if (rc == 0) {
1375                 /* we do not call this before to avoid lu_object_find() in
1376                  *  ->lvbo_update() holding another reference on the object.
1377                  * otherwise concurrent destroy can make the object unavailable
1378                  * for 2nd lu_object_find() waiting for the first reference
1379                  * to go... deadlock! */
1380                 res = ldlm_resource_get(ofd->ofd_namespace, NULL,
1381                                         &tsi->tsi_resid, LDLM_EXTENT, 0);
1382                 if (!IS_ERR(res)) {
1383                         ldlm_res_lvbo_update(res, NULL, 0);
1384                         ldlm_resource_putref(res);
1385                 }
1386         }
1387         return rc;
1388 }
1389
1390 /**
1391  * Destroy OST orphans.
1392  *
1393  * This is part of OST_CREATE RPC handling. If there is flag OBD_FL_DELORPHAN
1394  * set then we must destroy possible orphaned objects.
1395  *
1396  * \param[in] env       execution environment
1397  * \param[in] exp       OBD export
1398  * \param[in] ofd       OFD device
1399  * \param[in] oa        obdo structure for reply
1400  *
1401  * \retval              0 if successful
1402  * \retval              negative value on error
1403  */
1404 static int ofd_orphans_destroy(const struct lu_env *env,
1405                                struct obd_export *exp,
1406                                struct ofd_device *ofd, struct obdo *oa)
1407 {
1408         struct ofd_thread_info  *info   = ofd_info(env);
1409         struct lu_fid           *fid    = &info->fti_fid;
1410         struct ost_id           *oi     = &oa->o_oi;
1411         struct ofd_seq          *oseq;
1412         u64                      seq    = ostid_seq(oi);
1413         u64                      end_id = ostid_id(oi);
1414         u64                      last;
1415         u64                      oid;
1416         int                      skip_orphan;
1417         int                      rc     = 0;
1418
1419         ENTRY;
1420
1421         oseq = ofd_seq_get(ofd, seq);
1422         if (oseq == NULL) {
1423                 CERROR("%s: Can not find seq for "DOSTID"\n",
1424                        ofd_name(ofd), POSTID(oi));
1425                 RETURN(-EINVAL);
1426         }
1427
1428         *fid = oi->oi_fid;
1429         last = ofd_seq_last_oid(oseq);
1430         oid = last;
1431
1432         LASSERT(exp != NULL);
1433         skip_orphan = !!(exp_connect_flags(exp) & OBD_CONNECT_SKIP_ORPHAN);
1434
1435         if (OBD_FAIL_CHECK(OBD_FAIL_OST_NODESTROY))
1436                 goto done;
1437
1438         LCONSOLE(D_INFO, "%s: deleting orphan objects from "DOSTID
1439                  " to "DOSTID"\n", ofd_name(ofd), seq, end_id + 1, seq, last);
1440
1441         while (oid > end_id) {
1442                 rc = fid_set_id(fid, oid);
1443                 if (unlikely(rc != 0))
1444                         GOTO(out_put, rc);
1445
1446                 rc = ofd_destroy_by_fid(env, ofd, fid, 1);
1447                 if (rc != 0 && rc != -ENOENT && rc != -ESTALE &&
1448                     likely(rc != -EREMCHG && rc != -EINPROGRESS))
1449                         /* this is pretty fatal... */
1450                         CEMERG("%s: error destroying precreated id "
1451                                DFID": rc = %d\n",
1452                                ofd_name(ofd), PFID(fid), rc);
1453
1454                 oid--;
1455                 if (!skip_orphan) {
1456                         ofd_seq_last_oid_set(oseq, oid);
1457                         /* update last_id on disk periodically so that if we
1458                          * restart * we don't need to re-scan all of the just
1459                          * deleted objects. */
1460                         if ((oid & 511) == 0)
1461                                 ofd_seq_last_oid_write(env, ofd, oseq);
1462                 }
1463         }
1464
1465         CDEBUG(D_HA, "%s: after destroy: set last_id to "DOSTID"\n",
1466                ofd_name(ofd), seq, oid);
1467
1468 done:
1469         if (!skip_orphan) {
1470                 ofd_seq_last_oid_set(oseq, oid);
1471                 rc = ofd_seq_last_oid_write(env, ofd, oseq);
1472         } else {
1473                 /* don't reuse orphan object, return last used objid */
1474                 rc = ostid_set_id(oi, last);
1475         }
1476
1477         GOTO(out_put, rc);
1478
1479 out_put:
1480         ofd_seq_put(env, oseq);
1481         return rc;
1482 }
1483
1484 /**
1485  * OFD request handler for OST_CREATE RPC.
1486  *
1487  * This is OFD-specific part of request handling. Its main purpose is to
1488  * create new data objects on OST, but it also used to destroy orphans.
1489  *
1490  * \param[in] tsi       target session environment for this request
1491  *
1492  * \retval              0 if successful
1493  * \retval              negative value on error
1494  */
1495 static int ofd_create_hdl(struct tgt_session_info *tsi)
1496 {
1497         struct ptlrpc_request   *req = tgt_ses_req(tsi);
1498         struct ost_body         *repbody;
1499         const struct obdo       *oa = &tsi->tsi_ost_body->oa;
1500         struct obdo             *rep_oa;
1501         struct obd_export       *exp = tsi->tsi_exp;
1502         struct ofd_device       *ofd = ofd_exp(exp);
1503         u64                      seq = ostid_seq(&oa->o_oi);
1504         u64                      oid = ostid_id(&oa->o_oi);
1505         struct ofd_seq          *oseq;
1506         int                      sync_trans = 0;
1507         long                     granted = 0;
1508         ktime_t                  kstart = ktime_get();
1509         s64                      diff;
1510         int                      rc = 0;
1511
1512         ENTRY;
1513
1514         if (OBD_FAIL_CHECK(OBD_FAIL_OST_EROFS))
1515                 RETURN(-EROFS);
1516
1517         if (ofd->ofd_no_precreate)
1518                 return -EPERM;
1519
1520         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_OST_BODY);
1521         if (repbody == NULL)
1522                 RETURN(-ENOMEM);
1523
1524         down_read(&ofd->ofd_lastid_rwsem);
1525         /* Currently, for safe, we do not distinguish which LAST_ID is broken,
1526          * we may do that in the future.
1527          * Return -ENOSPC until the LAST_ID rebuilt. */
1528         if (unlikely(ofd->ofd_lastid_rebuilding))
1529                 GOTO(out_sem, rc = -ENOSPC);
1530
1531         rep_oa = &repbody->oa;
1532         rep_oa->o_oi = oa->o_oi;
1533
1534         LASSERT(oa->o_valid & OBD_MD_FLGROUP);
1535
1536         CDEBUG(D_INFO, "ofd_create("DOSTID")\n", POSTID(&oa->o_oi));
1537
1538         oseq = ofd_seq_load(tsi->tsi_env, ofd, seq);
1539         if (IS_ERR(oseq)) {
1540                 CERROR("%s: Can't find FID Sequence %#llx: rc = %ld\n",
1541                        ofd_name(ofd), seq, PTR_ERR(oseq));
1542                 GOTO(out_sem, rc = -EINVAL);
1543         }
1544
1545         if ((oa->o_valid & OBD_MD_FLFLAGS) &&
1546             (oa->o_flags & OBD_FL_RECREATE_OBJS)) {
1547                 if (!ofd_obd(ofd)->obd_recovering ||
1548                     oid > ofd_seq_last_oid(oseq)) {
1549                         CERROR("%s: recreate objid "DOSTID" > last id %llu"
1550                                "\n", ofd_name(ofd), POSTID(&oa->o_oi),
1551                                ofd_seq_last_oid(oseq));
1552                         GOTO(out_nolock, rc = -EINVAL);
1553                 }
1554                 /* Do nothing here, we re-create objects during recovery
1555                  * upon write replay, see ofd_preprw_write() */
1556                 GOTO(out_nolock, rc = 0);
1557         }
1558         /* former ofd_handle_precreate */
1559         if ((oa->o_valid & OBD_MD_FLFLAGS) &&
1560             (oa->o_flags & OBD_FL_DELORPHAN)) {
1561                 exp->exp_filter_data.fed_lastid_gen = ofd->ofd_lastid_gen;
1562
1563                 /* destroy orphans */
1564                 if (lustre_msg_get_conn_cnt(tgt_ses_req(tsi)->rq_reqmsg) <
1565                     exp->exp_conn_cnt) {
1566                         CERROR("%s: dropping old orphan cleanup request\n",
1567                                ofd_name(ofd));
1568                         GOTO(out_nolock, rc = 0);
1569                 }
1570                 /* This causes inflight precreates to abort and drop lock */
1571                 oseq->os_destroys_in_progress = 1;
1572                 mutex_lock(&oseq->os_create_lock);
1573                 if (!oseq->os_destroys_in_progress) {
1574                         CDEBUG(D_HA,
1575                                "%s:[%llu] destroys_in_progress already cleared\n",
1576                                ofd_name(ofd), seq);
1577                         rc = ostid_set_id(&rep_oa->o_oi,
1578                                           ofd_seq_last_oid(oseq));
1579                         GOTO(out, rc);
1580                 }
1581                 diff = oid - ofd_seq_last_oid(oseq);
1582                 CDEBUG(D_HA, "ofd_last_id() = %llu -> diff = %lld\n",
1583                        ofd_seq_last_oid(oseq), diff);
1584                 if (-diff > OST_MAX_PRECREATE) {
1585                         LCONSOLE(D_INFO, "%s: too large difference between MDS "
1586                                  "LAST_ID "DFID" (%llu) and OST LAST_ID "DFID" "
1587                                  "(%llu), trust the OST\n",
1588                                  ofd_name(ofd), PFID(&oa->o_oi.oi_fid), oid,
1589                                  PFID(&oseq->os_oi.oi_fid),
1590                                  ofd_seq_last_oid(oseq));
1591
1592                         /* Let MDS know that we are so far ahead. */
1593                         rc = ostid_set_id(&rep_oa->o_oi,
1594                                           ofd_seq_last_oid(oseq) + 1);
1595                 } else if (diff < 0) {
1596                         rc = ofd_orphans_destroy(tsi->tsi_env, exp,
1597                                                  ofd, rep_oa);
1598                         oseq->os_destroys_in_progress = 0;
1599                 } else {
1600                         /* XXX: Used by MDS for the first time! */
1601                         oseq->os_destroys_in_progress = 0;
1602                 }
1603         } else {
1604                 if (unlikely(exp->exp_filter_data.fed_lastid_gen !=
1605                              ofd->ofd_lastid_gen)) {
1606                         /* Keep the export ref so we can send the reply. */
1607                         ofd_obd_disconnect(class_export_get(exp));
1608                         GOTO(out_nolock, rc = -ENOTCONN);
1609                 }
1610
1611                 mutex_lock(&oseq->os_create_lock);
1612                 if (lustre_msg_get_conn_cnt(tgt_ses_req(tsi)->rq_reqmsg) <
1613                     exp->exp_conn_cnt) {
1614                         CERROR("%s: dropping old precreate request\n",
1615                                ofd_name(ofd));
1616                         GOTO(out, rc = 0);
1617                 }
1618                 /* only precreate if seq is 0, IDIF or normal and also o_id
1619                  * must be specfied */
1620                 if ((!fid_seq_is_mdt(seq) && !fid_seq_is_norm(seq) &&
1621                      !fid_seq_is_idif(seq)) || oid == 0) {
1622                         diff = 1; /* shouldn't we create this right now? */
1623                 } else {
1624                         diff = oid - ofd_seq_last_oid(oseq);
1625                         /* Do sync create if the seq is about to used up */
1626                         if (fid_seq_is_idif(seq) || fid_seq_is_mdt0(seq)) {
1627                                 if (unlikely(oid >= IDIF_MAX_OID - 1))
1628                                         sync_trans = 1;
1629                         } else if (fid_seq_is_norm(seq)) {
1630                                 if (unlikely(oid >=
1631                                              LUSTRE_DATA_SEQ_MAX_WIDTH - 1))
1632                                         sync_trans = 1;
1633                         } else {
1634                                 CERROR("%s : invalid o_seq "DOSTID"\n",
1635                                        ofd_name(ofd), POSTID(&oa->o_oi));
1636                                 GOTO(out, rc = -EINVAL);
1637                         }
1638
1639                         if (diff < 0) {
1640                                 /* LU-5648 */
1641                                 CERROR("%s: invalid precreate request for "
1642                                        DOSTID", last_id %llu. "
1643                                        "Likely MDS last_id corruption\n",
1644                                        ofd_name(ofd), POSTID(&oa->o_oi),
1645                                        ofd_seq_last_oid(oseq));
1646                                 GOTO(out, rc = -EINVAL);
1647                         }
1648                 }
1649         }
1650         if (diff > 0) {
1651                 time64_t enough_time = ktime_get_seconds() + DISK_TIMEOUT;
1652                 u64 next_id;
1653                 int created = 0;
1654                 int count;
1655                 int rc2;
1656
1657                 if (!(oa->o_valid & OBD_MD_FLFLAGS) ||
1658                     !(oa->o_flags & OBD_FL_DELORPHAN)) {
1659                         /* don't enforce grant during orphan recovery */
1660                         granted = tgt_grant_create(tsi->tsi_env,
1661                                                 ofd_obd(ofd)->obd_self_export,
1662                                                 &diff);
1663                         if (granted < 0) {
1664                                 rc = granted;
1665                                 granted = 0;
1666                                 CDEBUG(D_HA, "%s: failed to acquire grant "
1667                                        "space for precreate (%lld): rc = %d\n",
1668                                        ofd_name(ofd), diff, rc);
1669                                 diff = 0;
1670                         }
1671                 }
1672
1673                 /* This can happen if a new OST is formatted and installed
1674                  * in place of an old one at the same index.  Instead of
1675                  * precreating potentially millions of deleted old objects
1676                  * (possibly filling the OST), only precreate the last batch.
1677                  * LFSCK will eventually clean up any orphans. LU-14 */
1678                 if (diff > 5 * OST_MAX_PRECREATE) {
1679                         /* Message below is checked in conf-sanity test_122b */
1680                         LCONSOLE_WARN("%s: precreate FID "DOSTID" is over %lld higher than LAST_ID "DOSTID", only precreating the last %u objects. OST replaced or reformatted?\n",
1681                                       ofd_name(ofd), POSTID(&oa->o_oi), diff,
1682                                       POSTID(&oseq->os_oi),
1683                                       OST_MAX_PRECREATE / 2);
1684                         diff = OST_MAX_PRECREATE / 2;
1685                         ofd_seq_last_oid_set(oseq, ostid_id(&oa->o_oi) - diff);
1686                 }
1687
1688                 while (diff > 0) {
1689                         next_id = ofd_seq_last_oid(oseq) + 1;
1690                         count = ofd_precreate_batch(ofd, (int)diff);
1691
1692                         CDEBUG(D_HA, "%s: reserve %d objects in group %#llx"
1693                                " at %llu\n", ofd_name(ofd),
1694                                count, seq, next_id);
1695
1696                         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1697                             && ktime_get_seconds() > enough_time) {
1698                                 CDEBUG(D_HA, "%s: Slow creates, %d/%lld objects"
1699                                       " created at a rate of %d/s\n",
1700                                       ofd_name(ofd), created, diff + created,
1701                                       created / DISK_TIMEOUT);
1702                                 break;
1703                         }
1704
1705                         rc = ofd_precreate_objects(tsi->tsi_env, ofd, next_id,
1706                                                    oseq, count, sync_trans);
1707                         if (rc > 0) {
1708                                 created += rc;
1709                                 diff -= rc;
1710                         } else if (rc < 0) {
1711                                 break;
1712                         }
1713                 }
1714
1715                 if (diff > 0 &&
1716                     lustre_msg_get_flags(req->rq_reqmsg) & MSG_REPLAY)
1717                         LCONSOLE_WARN("%s: can't create the same count of"
1718                                       " objects when replaying the request"
1719                                       " (diff is %lld). see LU-4621\n",
1720                                       ofd_name(ofd), diff);
1721
1722                 if (created > 0)
1723                         /* some objects got created, we can return
1724                          * them, even if last creation failed */
1725                         rc = 0;
1726                 else
1727                         CERROR("%s: unable to precreate: rc = %d\n",
1728                                ofd_name(ofd), rc);
1729
1730                 if (!(oa->o_valid & OBD_MD_FLFLAGS) ||
1731                     !(oa->o_flags & OBD_FL_DELORPHAN)) {
1732                         tgt_grant_commit(ofd_obd(ofd)->obd_self_export,
1733                                          granted, rc);
1734                         granted = 0;
1735                 }
1736
1737                 rc2 = ostid_set_id(&rep_oa->o_oi, ofd_seq_last_oid(oseq));
1738                 rc = rc ? : rc2;
1739         }
1740         EXIT;
1741         ofd_counter_incr(exp, LPROC_OFD_STATS_CREATE,
1742                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
1743         if (unlikely(!oseq->os_last_id_synced))
1744                 oseq->os_last_id_synced = 1;
1745 out:
1746         mutex_unlock(&oseq->os_create_lock);
1747 out_nolock:
1748         if (rc == 0)
1749                 rep_oa->o_valid |= OBD_MD_FLID | OBD_MD_FLGROUP;
1750         ofd_seq_put(tsi->tsi_env, oseq);
1751
1752 out_sem:
1753         up_read(&ofd->ofd_lastid_rwsem);
1754         return rc;
1755 }
1756
1757 /**
1758  * OFD request handler for OST_DESTROY RPC.
1759  *
1760  * This is OFD-specific part of request handling. It destroys data objects
1761  * related to destroyed object on MDT.
1762  *
1763  * \param[in] tsi       target session environment for this request
1764  *
1765  * \retval              0 if successful
1766  * \retval              negative value on error
1767  */
1768 static int ofd_destroy_hdl(struct tgt_session_info *tsi)
1769 {
1770         const struct ost_body   *body = tsi->tsi_ost_body;
1771         struct ost_body         *repbody;
1772         struct ofd_device       *ofd = ofd_exp(tsi->tsi_exp);
1773         struct ofd_thread_info  *fti = tsi2ofd_info(tsi);
1774         struct lu_fid           *fid = &fti->fti_fid;
1775         ktime_t                  kstart = ktime_get();
1776         u64                      oid;
1777         u32                      count;
1778         int                      rc = 0;
1779
1780         ENTRY;
1781
1782         if (OBD_FAIL_CHECK(OBD_FAIL_OST_EROFS))
1783                 RETURN(-EROFS);
1784
1785         /* This is old case for clients before Lustre 2.4 */
1786         /* If there's a DLM request, cancel the locks mentioned in it */
1787         if (req_capsule_field_present(tsi->tsi_pill, &RMF_DLM_REQ,
1788                                       RCL_CLIENT)) {
1789                 struct ldlm_request *dlm;
1790
1791                 dlm = req_capsule_client_get(tsi->tsi_pill, &RMF_DLM_REQ);
1792                 if (dlm == NULL)
1793                         RETURN(-EFAULT);
1794                 ldlm_request_cancel(tgt_ses_req(tsi), dlm, 0, LATF_SKIP);
1795         }
1796
1797         *fid = body->oa.o_oi.oi_fid;
1798         oid = ostid_id(&body->oa.o_oi);
1799         LASSERT(oid != 0);
1800
1801         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_OST_BODY);
1802
1803         /* check that o_misc makes sense */
1804         if (body->oa.o_valid & OBD_MD_FLOBJCOUNT)
1805                 count = body->oa.o_misc;
1806         else
1807                 count = 1; /* default case - single destroy */
1808
1809         CDEBUG(D_HA, "%s: Destroy object "DOSTID" count %d\n", ofd_name(ofd),
1810                POSTID(&body->oa.o_oi), count);
1811
1812         while (count > 0) {
1813                 int lrc;
1814
1815                 lrc = ofd_destroy_by_fid(tsi->tsi_env, ofd, fid, 0);
1816                 if (lrc == -ENOENT) {
1817                         CDEBUG(D_INODE,
1818                                "%s: destroying non-existent object "DFID"\n",
1819                                ofd_name(ofd), PFID(fid));
1820                         /* rewrite rc with -ENOENT only if it is 0 */
1821                         if (rc == 0)
1822                                 rc = lrc;
1823                 } else if (lrc != 0) {
1824                         CERROR("%s: error destroying object "DFID": %d\n",
1825                                ofd_name(ofd), PFID(fid), lrc);
1826                         rc = lrc;
1827                 }
1828
1829                 count--;
1830                 oid++;
1831                 lrc = fid_set_id(fid, oid);
1832                 if (unlikely(lrc != 0 && count > 0))
1833                         GOTO(out, rc = lrc);
1834         }
1835
1836         ofd_counter_incr(tsi->tsi_exp, LPROC_OFD_STATS_DESTROY,
1837                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
1838
1839         GOTO(out, rc);
1840
1841 out:
1842         fid_to_ostid(fid, &repbody->oa.o_oi);
1843         return rc;
1844 }
1845
1846 /**
1847  * OFD request handler for OST_STATFS RPC.
1848  *
1849  * This function gets statfs data from storage as part of request
1850  * processing.
1851  *
1852  * \param[in] tsi       target session environment for this request
1853  *
1854  * \retval              0 if successful
1855  * \retval              negative value on error
1856  */
1857 static int ofd_statfs_hdl(struct tgt_session_info *tsi)
1858 {
1859         ktime_t                  kstart = ktime_get();
1860         struct obd_statfs       *osfs;
1861         int                      rc;
1862
1863         ENTRY;
1864
1865         OBD_FAIL_TIMEOUT(OBD_FAIL_OST_STATFS_DELAY, 10);
1866
1867         osfs = req_capsule_server_get(tsi->tsi_pill, &RMF_OBD_STATFS);
1868
1869         rc = ofd_statfs(tsi->tsi_env, tsi->tsi_exp, osfs,
1870                         ktime_get_seconds() - OBD_STATFS_CACHE_SECONDS, 0);
1871         if (rc != 0)
1872                 CERROR("%s: statfs failed: rc = %d\n",
1873                        tgt_name(tsi->tsi_tgt), rc);
1874
1875         if (OBD_FAIL_CHECK(OBD_FAIL_OST_STATFS_EINPROGRESS))
1876                 rc = -EINPROGRESS;
1877
1878         ofd_counter_incr(tsi->tsi_exp, LPROC_OFD_STATS_STATFS,
1879                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
1880
1881         RETURN(rc);
1882 }
1883
1884 /**
1885  * OFD request handler for OST_SYNC RPC.
1886  *
1887  * Sync object data or all filesystem data to the disk and pack the
1888  * result in reply.
1889  *
1890  * \param[in] tsi       target session environment for this request
1891  *
1892  * \retval              0 if successful
1893  * \retval              negative value on error
1894  */
1895 static int ofd_sync_hdl(struct tgt_session_info *tsi)
1896 {
1897         struct ost_body         *body = tsi->tsi_ost_body;
1898         struct ost_body         *repbody;
1899         struct ofd_thread_info  *fti = tsi2ofd_info(tsi);
1900         struct ofd_device       *ofd = ofd_exp(tsi->tsi_exp);
1901         struct ofd_object       *fo = NULL;
1902         ktime_t                  kstart = ktime_get();
1903         int                      rc = 0;
1904
1905         ENTRY;
1906
1907         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_OST_BODY);
1908
1909         /* if no objid is specified, it means "sync whole filesystem" */
1910         if (!fid_is_zero(&tsi->tsi_fid)) {
1911                 fo = ofd_object_find_exists(tsi->tsi_env, ofd, &tsi->tsi_fid);
1912                 if (IS_ERR(fo))
1913                         RETURN(PTR_ERR(fo));
1914         }
1915
1916         rc = tgt_sync(tsi->tsi_env, tsi->tsi_tgt,
1917                       fo != NULL ? ofd_object_child(fo) : NULL,
1918                       repbody->oa.o_size, repbody->oa.o_blocks);
1919         if (rc)
1920                 GOTO(put, rc);
1921
1922         ofd_counter_incr(tsi->tsi_exp, LPROC_OFD_STATS_SYNC,
1923                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
1924         if (fo == NULL)
1925                 RETURN(0);
1926
1927         repbody->oa.o_oi = body->oa.o_oi;
1928         repbody->oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
1929
1930         rc = ofd_attr_get(tsi->tsi_env, fo, &fti->fti_attr);
1931         if (rc == 0)
1932                 obdo_from_la(&repbody->oa, &fti->fti_attr,
1933                              OFD_VALID_FLAGS);
1934         else
1935                 /* don't return rc from getattr */
1936                 rc = 0;
1937         EXIT;
1938 put:
1939         if (fo != NULL)
1940                 ofd_object_put(tsi->tsi_env, fo);
1941         return rc;
1942 }
1943
1944 /**
1945  * OFD request handler for OST_FALLOCATE RPC.
1946  *
1947  * This is part of request processing. Validate request fields,
1948  * preallocate the given OFD object and pack reply.
1949  *
1950  * \param[in] tsi       target session environment for this request
1951  *
1952  * \retval              0 if successful
1953  * \retval              negative value on error
1954  */
1955 static int ofd_fallocate_hdl(struct tgt_session_info *tsi)
1956 {
1957         struct obdo *oa = &tsi->tsi_ost_body->oa;
1958         struct ost_body *repbody;
1959         struct ofd_thread_info *info = tsi2ofd_info(tsi);
1960         struct ldlm_namespace *ns = tsi->tsi_tgt->lut_obd->obd_namespace;
1961         struct ldlm_resource *res;
1962         struct ofd_object *fo;
1963         __u64 flags = 0;
1964         struct lustre_handle lh = { 0, };
1965         int rc, mode;
1966         __u64 start, end;
1967         bool srvlock;
1968         ktime_t kstart = ktime_get();
1969
1970         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_OST_BODY);
1971         if (repbody == NULL)
1972                 RETURN(err_serious(-ENOMEM));
1973
1974         /*
1975          * fallocate start and end are passed in o_size, o_blocks
1976          * on the wire.
1977          */
1978         if ((oa->o_valid & (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS)) !=
1979             (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS))
1980                 RETURN(err_serious(-EPROTO));
1981
1982         start = oa->o_size;
1983         end = oa->o_blocks;
1984         mode = oa->o_falloc_mode;
1985         /*
1986          * mode == 0 (which is standard prealloc) and PUNCH is supported
1987          * Rest of mode options are not supported yet.
1988          */
1989         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
1990                 RETURN(-EOPNOTSUPP);
1991
1992         /* PUNCH_HOLE mode should always be accompanied with KEEP_SIZE flag
1993          * Check that and add the missing flag for such invalid call with
1994          * warning.
1995          */
1996         if (mode & FALLOC_FL_PUNCH_HOLE && !(mode & FALLOC_FL_KEEP_SIZE)) {
1997                 CWARN("%s: PUNCH mode misses KEEP_SIZE flag, setting it\n",
1998                       tsi->tsi_tgt->lut_obd->obd_name);
1999                 mode |= FALLOC_FL_KEEP_SIZE;
2000         }
2001
2002         repbody->oa.o_oi = oa->o_oi;
2003         repbody->oa.o_valid = OBD_MD_FLID;
2004
2005         srvlock = oa->o_valid & OBD_MD_FLFLAGS &&
2006                   oa->o_flags & OBD_FL_SRVLOCK;
2007
2008         if (srvlock) {
2009                 rc = tgt_extent_lock(tsi->tsi_env, ns, &tsi->tsi_resid,
2010                                      start, end, &lh, LCK_PW, &flags);
2011                 if (rc != 0)
2012                         RETURN(rc);
2013         }
2014
2015         fo = ofd_object_find_exists(tsi->tsi_env, ofd_exp(tsi->tsi_exp),
2016                                     &tsi->tsi_fid);
2017         if (IS_ERR(fo))
2018                 GOTO(out, rc = PTR_ERR(fo));
2019
2020         la_from_obdo(&info->fti_attr, oa,
2021                      OBD_MD_FLMTIME | OBD_MD_FLATIME | OBD_MD_FLCTIME);
2022
2023         rc = ofd_object_fallocate(tsi->tsi_env, fo, start, end, mode,
2024                                  &info->fti_attr, oa);
2025         if (rc)
2026                 GOTO(out_put, rc);
2027
2028         rc = ofd_attr_get(tsi->tsi_env, fo, &info->fti_attr);
2029         if (rc == 0)
2030                 obdo_from_la(&repbody->oa, &info->fti_attr,
2031                              OFD_VALID_FLAGS);
2032         else
2033                 rc = 0;
2034
2035         ofd_counter_incr(tsi->tsi_exp, LPROC_OFD_STATS_PREALLOC,
2036                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
2037
2038         EXIT;
2039 out_put:
2040         ofd_object_put(tsi->tsi_env, fo);
2041 out:
2042         if (srvlock)
2043                 tgt_data_unlock(&lh, LCK_PW);
2044         if (rc == 0) {
2045                 res = ldlm_resource_get(ns, NULL, &tsi->tsi_resid,
2046                                         LDLM_EXTENT, 0);
2047                 if (!IS_ERR(res)) {
2048                         struct ost_lvb *res_lvb;
2049
2050                         ldlm_res_lvbo_update(res, NULL, 0);
2051                         res_lvb = res->lr_lvb_data;
2052                         /* Blocks */
2053                         repbody->oa.o_valid |= OBD_MD_FLBLOCKS;
2054                         repbody->oa.o_blocks = res_lvb->lvb_blocks;
2055                         /* Size */
2056                         repbody->oa.o_valid |= OBD_MD_FLSIZE;
2057                         repbody->oa.o_size = res_lvb->lvb_size;
2058
2059                         ldlm_resource_putref(res);
2060                 }
2061         }
2062
2063         RETURN(rc);
2064 }
2065
2066 /**
2067  * OFD request handler for OST_PUNCH RPC.
2068  *
2069  * This is part of request processing. Validate request fields,
2070  * punch (truncate) the given OFD object and pack reply.
2071  *
2072  * \param[in] tsi       target session environment for this request
2073  *
2074  * \retval              0 if successful
2075  * \retval              negative value on error
2076  */
2077 static int ofd_punch_hdl(struct tgt_session_info *tsi)
2078 {
2079         const struct obdo       *oa = &tsi->tsi_ost_body->oa;
2080         struct ost_body         *repbody;
2081         struct ofd_thread_info  *info = tsi2ofd_info(tsi);
2082         struct ldlm_namespace   *ns = tsi->tsi_tgt->lut_obd->obd_namespace;
2083         struct ldlm_resource    *res;
2084         struct ofd_object       *fo;
2085         __u64                    flags = 0;
2086         struct lustre_handle     lh = { 0, };
2087         __u64                    start, end;
2088         bool                     srvlock;
2089         ktime_t                  kstart = ktime_get();
2090         int                      rc;
2091
2092         ENTRY;
2093
2094         OBD_FAIL_TIMEOUT(OBD_FAIL_OST_PAUSE_PUNCH, cfs_fail_val);
2095
2096         if ((oa->o_valid & (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS)) !=
2097             (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS))
2098                 RETURN(err_serious(-EPROTO));
2099
2100         repbody = req_capsule_server_get(tsi->tsi_pill, &RMF_OST_BODY);
2101         if (repbody == NULL)
2102                 RETURN(err_serious(-ENOMEM));
2103
2104         /* punch start,end are passed in o_size,o_blocks throught wire */
2105         start = oa->o_size;
2106         end = oa->o_blocks;
2107
2108         if (end != OBD_OBJECT_EOF) /* Only truncate is supported */
2109                 RETURN(-EPROTO);
2110
2111         /* standard truncate optimization: if file body is completely
2112          * destroyed, don't send data back to the server. */
2113         if (start == 0)
2114                 flags |= LDLM_FL_AST_DISCARD_DATA;
2115
2116         repbody->oa.o_oi = oa->o_oi;
2117         repbody->oa.o_valid = OBD_MD_FLID;
2118
2119         srvlock = oa->o_valid & OBD_MD_FLFLAGS &&
2120                   oa->o_flags & OBD_FL_SRVLOCK;
2121
2122         if (srvlock) {
2123                 rc = tgt_extent_lock(tsi->tsi_env, ns, &tsi->tsi_resid, start,
2124                                      end, &lh, LCK_PW, &flags);
2125                 if (rc != 0)
2126                         RETURN(rc);
2127         }
2128
2129         CDEBUG(D_INODE, "calling punch for object "DFID", valid = %#llx"
2130                ", start = %lld, end = %lld\n", PFID(&tsi->tsi_fid),
2131                oa->o_valid, start, end);
2132
2133         fo = ofd_object_find_exists(tsi->tsi_env, ofd_exp(tsi->tsi_exp),
2134                                     &tsi->tsi_fid);
2135         if (IS_ERR(fo))
2136                 GOTO(out, rc = PTR_ERR(fo));
2137
2138         la_from_obdo(&info->fti_attr, oa,
2139                      OBD_MD_FLMTIME | OBD_MD_FLATIME | OBD_MD_FLCTIME);
2140         info->fti_attr.la_size = start;
2141         info->fti_attr.la_valid |= LA_SIZE;
2142
2143         rc = ofd_object_punch(tsi->tsi_env, fo, start, end, &info->fti_attr,
2144                               (struct obdo *)oa);
2145         if (rc)
2146                 GOTO(out_put, rc);
2147
2148         ofd_counter_incr(tsi->tsi_exp, LPROC_OFD_STATS_PUNCH,
2149                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
2150         EXIT;
2151 out_put:
2152         ofd_object_put(tsi->tsi_env, fo);
2153 out:
2154         if (srvlock)
2155                 tgt_data_unlock(&lh, LCK_PW);
2156         if (rc == 0) {
2157                 /* we do not call this before to avoid lu_object_find() in
2158                  *  ->lvbo_update() holding another reference on the object.
2159                  * otherwise concurrent destroy can make the object unavailable
2160                  * for 2nd lu_object_find() waiting for the first reference
2161                  * to go... deadlock! */
2162                 res = ldlm_resource_get(ns, NULL, &tsi->tsi_resid,
2163                                         LDLM_EXTENT, 0);
2164                 if (!IS_ERR(res)) {
2165                         struct ost_lvb *res_lvb;
2166
2167                         ldlm_res_lvbo_update(res, NULL, 0);
2168                         res_lvb = res->lr_lvb_data;
2169                         repbody->oa.o_valid |= OBD_MD_FLBLOCKS;
2170                         repbody->oa.o_blocks = res_lvb->lvb_blocks;
2171                         ldlm_resource_putref(res);
2172                 }
2173         }
2174         return rc;
2175 }
2176
2177 static int ofd_ladvise_prefetch(const struct lu_env *env,
2178                                 struct ofd_object *fo,
2179                                 struct niobuf_local *lnb,
2180                                 __u64 start, __u64 end, enum dt_bufs_type dbt)
2181 {
2182         struct ofd_thread_info *info = ofd_info(env);
2183         pgoff_t start_index, end_index, pages;
2184         struct niobuf_remote rnb;
2185         unsigned long nr_local;
2186         int rc = 0;
2187
2188         if (end <= start)
2189                 RETURN(-EINVAL);
2190
2191         ofd_read_lock(env, fo);
2192         if (!ofd_object_exists(fo))
2193                 GOTO(out_unlock, rc = -ENOENT);
2194
2195         rc = ofd_attr_get(env, fo, &info->fti_attr);
2196         if (rc)
2197                 GOTO(out_unlock, rc);
2198
2199         if (end > info->fti_attr.la_size)
2200                 end = info->fti_attr.la_size;
2201
2202         if (end <= start)
2203                 GOTO(out_unlock, rc);
2204
2205         /* We need page aligned offset and length */
2206         start_index = start >> PAGE_SHIFT;
2207         end_index = (end - 1) >> PAGE_SHIFT;
2208         pages = end_index - start_index + 1;
2209         while (pages > 0) {
2210                 nr_local = pages <= PTLRPC_MAX_BRW_PAGES ? pages :
2211                         PTLRPC_MAX_BRW_PAGES;
2212                 rnb.rnb_offset = start_index << PAGE_SHIFT;
2213                 rnb.rnb_len = nr_local << PAGE_SHIFT;
2214                 rc = dt_bufs_get(env, ofd_object_child(fo), &rnb, lnb,
2215                                  PTLRPC_MAX_BRW_PAGES, dbt);
2216                 if (unlikely(rc < 0))
2217                         break;
2218                 nr_local = rc;
2219                 rc = dt_read_prep(env, ofd_object_child(fo), lnb, nr_local);
2220                 dt_bufs_put(env, ofd_object_child(fo), lnb, nr_local);
2221                 if (unlikely(rc))
2222                         break;
2223                 start_index += nr_local;
2224                 pages -= nr_local;
2225         }
2226
2227 out_unlock:
2228         ofd_read_unlock(env, fo);
2229         RETURN(rc);
2230 }
2231
2232 /**
2233  * OFD request handler for OST_LADVISE RPC.
2234  *
2235  * Tune cache or perfetch policies according to advices.
2236  *
2237  * \param[in] tsi       target session environment for this request
2238  *
2239  * \retval              0 if successful
2240  * \retval              negative errno on error
2241  */
2242 static int ofd_ladvise_hdl(struct tgt_session_info *tsi)
2243 {
2244         struct ptlrpc_request *req = tgt_ses_req(tsi);
2245         struct obd_export *exp = tsi->tsi_exp;
2246         struct ofd_device *ofd = ofd_exp(exp);
2247         struct ost_body *body, *repbody;
2248         struct ofd_thread_info *info;
2249         struct ofd_object *fo;
2250         struct ptlrpc_thread *svc_thread = req->rq_svc_thread;
2251         const struct lu_env *env = svc_thread->t_env;
2252         struct tgt_thread_big_cache *tbc = svc_thread->t_data;
2253         enum dt_bufs_type dbt = DT_BUFS_TYPE_READAHEAD;
2254         struct lu_ladvise *ladvise;
2255         int num_advise;
2256         struct ladvise_hdr *ladvise_hdr;
2257         struct obd_ioobj ioo;
2258         struct lustre_handle lockh = { 0 };
2259         __u64 flags = 0;
2260         int i;
2261         struct dt_object *dob;
2262         __u64 start;
2263         __u64 end;
2264         int rc = 0;
2265         ENTRY;
2266
2267         CFS_FAIL_TIMEOUT(OBD_FAIL_OST_LADVISE_PAUSE, cfs_fail_val);
2268         body = tsi->tsi_ost_body;
2269
2270         if ((body->oa.o_valid & OBD_MD_FLID) != OBD_MD_FLID)
2271                 RETURN(err_serious(-EPROTO));
2272
2273         ladvise_hdr = req_capsule_client_get(tsi->tsi_pill,
2274                                              &RMF_OST_LADVISE_HDR);
2275         if (ladvise_hdr == NULL)
2276                 RETURN(err_serious(-EPROTO));
2277
2278         if (ladvise_hdr->lah_magic != LADVISE_MAGIC ||
2279             ladvise_hdr->lah_count < 1)
2280                 RETURN(err_serious(-EPROTO));
2281
2282         if ((ladvise_hdr->lah_flags & (~LF_MASK)) != 0)
2283                 RETURN(err_serious(-EPROTO));
2284
2285         ladvise = req_capsule_client_get(tsi->tsi_pill, &RMF_OST_LADVISE);
2286         if (ladvise == NULL)
2287                 RETURN(err_serious(-EPROTO));
2288
2289         num_advise = req_capsule_get_size(&req->rq_pill,
2290                                           &RMF_OST_LADVISE, RCL_CLIENT) /
2291                                           sizeof(*ladvise);
2292         if (num_advise < ladvise_hdr->lah_count)
2293                 RETURN(err_serious(-EPROTO));
2294
2295         repbody = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
2296         repbody->oa = body->oa;
2297
2298         info = ofd_info_init(env, exp);
2299
2300         rc = ostid_to_fid(&info->fti_fid, &body->oa.o_oi,
2301                           ofd->ofd_lut.lut_lsd.lsd_osd_index);
2302         if (rc != 0)
2303                 RETURN(rc);
2304
2305         fo = ofd_object_find(env, ofd, &info->fti_fid);
2306         if (IS_ERR(fo)) {
2307                 rc = PTR_ERR(fo);
2308                 RETURN(rc);
2309         }
2310         LASSERT(fo != NULL);
2311         dob = ofd_object_child(fo);
2312
2313         if (ptlrpc_connection_is_local(exp->exp_connection))
2314                 dbt |= DT_BUFS_TYPE_LOCAL;
2315
2316         for (i = 0; i < num_advise; i++, ladvise++) {
2317                 start = ladvise->lla_start;
2318                 end = ladvise->lla_end;
2319                 if (end <= start) {
2320                         rc = err_serious(-EPROTO);
2321                         break;
2322                 }
2323
2324                 /* Handle different advice types */
2325                 switch (ladvise->lla_advice) {
2326                 default:
2327                         rc = -ENOTSUPP;
2328                         break;
2329                 case LU_LADVISE_WILLREAD:
2330                         if (tbc == NULL)
2331                                 RETURN(-ENOMEM);
2332
2333                         ioo.ioo_oid = body->oa.o_oi;
2334                         ioo.ioo_bufcnt = 1;
2335                         rc = tgt_extent_lock(env, exp->exp_obd->obd_namespace,
2336                                              &tsi->tsi_resid, start, end - 1,
2337                                              &lockh, LCK_PR, &flags);
2338                         if (rc != 0)
2339                                 break;
2340
2341                         req->rq_status = ofd_ladvise_prefetch(env, fo,
2342                                                               tbc->local,
2343                                                               start, end, dbt);
2344                         tgt_data_unlock(&lockh, LCK_PR);
2345                         break;
2346                 case LU_LADVISE_DONTNEED:
2347                         rc = dt_ladvise(env, dob, ladvise->lla_start,
2348                                         ladvise->lla_end, LU_LADVISE_DONTNEED);
2349                         break;
2350                 }
2351                 if (rc != 0)
2352                         break;
2353         }
2354
2355         ofd_object_put(env, fo);
2356         req->rq_status = rc;
2357         RETURN(rc);
2358 }
2359
2360 /**
2361  * OFD request handler for OST_QUOTACTL RPC.
2362  *
2363  * This is part of request processing to validate incoming request fields,
2364  * get the requested data from OSD and pack reply.
2365  *
2366  * \param[in] tsi       target session environment for this request
2367  *
2368  * \retval              0 if successful
2369  * \retval              negative value on error
2370  */
2371 static int ofd_quotactl(struct tgt_session_info *tsi)
2372 {
2373         struct obd_quotactl *oqctl, *repoqc;
2374         struct lu_nodemap *nodemap;
2375         ktime_t kstart = ktime_get();
2376         int id;
2377         int rc;
2378
2379         ENTRY;
2380
2381         oqctl = req_capsule_client_get(tsi->tsi_pill, &RMF_OBD_QUOTACTL);
2382         if (oqctl == NULL)
2383                 RETURN(err_serious(-EPROTO));
2384
2385         repoqc = req_capsule_server_get(tsi->tsi_pill, &RMF_OBD_QUOTACTL);
2386         if (repoqc == NULL)
2387                 RETURN(err_serious(-ENOMEM));
2388
2389         *repoqc = *oqctl;
2390
2391         nodemap = nodemap_get_from_exp(tsi->tsi_exp);
2392         if (IS_ERR(nodemap))
2393                 RETURN(PTR_ERR(nodemap));
2394
2395         id = repoqc->qc_id;
2396         if (oqctl->qc_type == USRQUOTA)
2397                 id = nodemap_map_id(nodemap, NODEMAP_UID,
2398                                     NODEMAP_CLIENT_TO_FS,
2399                                     repoqc->qc_id);
2400         else if (oqctl->qc_type == GRPQUOTA)
2401                 id = nodemap_map_id(nodemap, NODEMAP_GID,
2402                                     NODEMAP_CLIENT_TO_FS,
2403                                     repoqc->qc_id);
2404         else if (oqctl->qc_type == PRJQUOTA)
2405                 id = nodemap_map_id(nodemap, NODEMAP_PROJID,
2406                                     NODEMAP_CLIENT_TO_FS,
2407                                     repoqc->qc_id);
2408
2409         nodemap_putref(nodemap);
2410
2411         if (repoqc->qc_id != id)
2412                 swap(repoqc->qc_id, id);
2413
2414         rc = lquotactl_slv(tsi->tsi_env, tsi->tsi_tgt->lut_bottom, repoqc);
2415
2416         ofd_counter_incr(tsi->tsi_exp, LPROC_OFD_STATS_QUOTACTL,
2417                          tsi->tsi_jobid, ktime_us_delta(ktime_get(), kstart));
2418
2419         if (repoqc->qc_id != id)
2420                 swap(repoqc->qc_id, id);
2421
2422         RETURN(rc);
2423 }
2424
2425 /**
2426  * Prolong lock timeout for the given extent.
2427  *
2428  * This function finds all locks related with incoming request and
2429  * prolongs their timeout.
2430  *
2431  * If a client is holding a lock for a long time while it sends
2432  * read or write RPCs to the OST for the object under this lock,
2433  * then we don't want the OST to evict the client. Otherwise,
2434  * if the network or disk is very busy then the client may not
2435  * be able to make any progress to clear out dirty pages under
2436  * the lock and the application will fail.
2437  *
2438  * Every time a Bulk Read/Write (BRW) request arrives for the object
2439  * covered by the lock, extend the timeout on that lock. The RPC should
2440  * contain a lock handle for the lock it is using, but this
2441  * isn't handled correctly by all client versions, and the
2442  * request may cover multiple locks.
2443  *
2444  * \param[in] tsi       target session environment for this request
2445  * \param[in] data      struct of data to prolong locks
2446  *
2447  */
2448 static void ofd_prolong_extent_locks(struct tgt_session_info *tsi,
2449                                     struct ldlm_prolong_args *data)
2450 {
2451         struct obdo             *oa  = &tsi->tsi_ost_body->oa;
2452         struct ldlm_lock        *lock;
2453
2454         ENTRY;
2455
2456         data->lpa_timeout = prolong_timeout(tgt_ses_req(tsi));
2457         data->lpa_export = tsi->tsi_exp;
2458         data->lpa_resid = tsi->tsi_resid;
2459
2460         CDEBUG(D_RPCTRACE, "Prolong locks for req %p with x%llu"
2461                " ext(%llu->%llu)\n", tgt_ses_req(tsi),
2462                tgt_ses_req(tsi)->rq_xid, data->lpa_extent.start,
2463                data->lpa_extent.end);
2464
2465         if (oa->o_valid & OBD_MD_FLHANDLE) {
2466                 /* mostly a request should be covered by only one lock, try
2467                  * fast path. */
2468                 lock = ldlm_handle2lock(&oa->o_handle);
2469                 if (lock != NULL) {
2470                         /* Fast path to check if the lock covers the whole IO
2471                          * region exclusively. */
2472                         if (ldlm_extent_contain(&lock->l_policy_data.l_extent,
2473                                                 &data->lpa_extent)) {
2474                                 /* bingo */
2475                                 LASSERT(lock->l_export == data->lpa_export);
2476                                 ldlm_lock_prolong_one(lock, data);
2477                                 LDLM_LOCK_PUT(lock);
2478                                 if (data->lpa_locks_cnt > 0)
2479                                         RETURN_EXIT;
2480                                 /* The lock was destroyed probably lets try
2481                                  * resource tree. */
2482                         } else {
2483                                 lock->l_last_used = ktime_get();
2484                                 LDLM_LOCK_PUT(lock);
2485                         }
2486                 }
2487         }
2488
2489         ldlm_resource_prolong(data);
2490         EXIT;
2491 }
2492
2493 /**
2494  * Implementation of ptlrpc_hpreq_ops::hpreq_lock_match for OFD RW requests.
2495  *
2496  * Determine if \a lock and the lock from request \a req are equivalent
2497  * by comparing their resource names, modes, and extents.
2498  *
2499  * It is used to give priority to read and write RPCs being done
2500  * under this lock so that the client can drop the contended
2501  * lock more quickly and let other clients use it. This improves
2502  * overall performance in the case where the first client gets a
2503  * very large lock extent that prevents other clients from
2504  * submitting their writes.
2505  *
2506  * \param[in] req       ptlrpc_request being processed
2507  * \param[in] lock      contended lock to match
2508  *
2509  * \retval              1 if lock is matched
2510  * \retval              0 otherwise
2511  */
2512 static int ofd_rw_hpreq_lock_match(struct ptlrpc_request *req,
2513                                    struct ldlm_lock *lock)
2514 {
2515         struct niobuf_remote *rnb;
2516         struct obd_ioobj *ioo;
2517         enum ldlm_mode  mode;
2518         struct ldlm_extent ext;
2519         __u32 opc = lustre_msg_get_opc(req->rq_reqmsg);
2520
2521         ENTRY;
2522
2523         ioo = req_capsule_client_get(&req->rq_pill, &RMF_OBD_IOOBJ);
2524         LASSERT(ioo != NULL);
2525
2526         rnb = req_capsule_client_get(&req->rq_pill, &RMF_NIOBUF_REMOTE);
2527         LASSERT(rnb != NULL);
2528
2529         ext.start = rnb->rnb_offset;
2530         rnb += ioo->ioo_bufcnt - 1;
2531         ext.end = rnb->rnb_offset + rnb->rnb_len - 1;
2532
2533         LASSERT(lock->l_resource != NULL);
2534         if (!ostid_res_name_eq(&ioo->ioo_oid, &lock->l_resource->lr_name))
2535                 RETURN(0);
2536
2537         /* a bulk write can only hold a reference on a PW extent lock
2538          * or GROUP lock.
2539          */
2540         mode = LCK_PW | LCK_GROUP;
2541         if (opc == OST_READ)
2542                 /* whereas a bulk read can be protected by either a PR or PW
2543                  * extent lock */
2544                 mode |= LCK_PR;
2545
2546         if (!(lock->l_granted_mode & mode))
2547                 RETURN(0);
2548
2549         RETURN(ldlm_extent_overlap(&lock->l_policy_data.l_extent, &ext));
2550 }
2551
2552 /**
2553  * Implementation of ptlrpc_hpreq_ops::hpreq_lock_check for OFD RW requests.
2554  *
2555  * Check for whether the given PTLRPC request (\a req) is blocking
2556  * an LDLM lock cancel. Also checks whether the request is covered by an LDLM
2557  * lock.
2558  *
2559  * \param[in] req       the incoming request
2560  *
2561  * \retval              1 if \a req is blocking an LDLM lock cancel
2562  * \retval              0 if it is not
2563  * \retval              -ESTALE if lock is not found
2564  */
2565 static int ofd_rw_hpreq_check(struct ptlrpc_request *req)
2566 {
2567         struct tgt_session_info *tsi;
2568         struct obd_ioobj        *ioo;
2569         struct niobuf_remote    *rnb;
2570         int opc;
2571         struct ldlm_prolong_args pa = { 0 };
2572
2573         ENTRY;
2574
2575         /* Don't use tgt_ses_info() to get session info, because lock_match()
2576          * can be called while request has no processing thread yet. */
2577         tsi = lu_context_key_get(&req->rq_session, &tgt_session_key);
2578
2579         /*
2580          * Use LASSERT below because malformed RPCs should have
2581          * been filtered out in tgt_hpreq_handler().
2582          */
2583         opc = lustre_msg_get_opc(req->rq_reqmsg);
2584         LASSERT(opc == OST_READ || opc == OST_WRITE);
2585
2586         ioo = req_capsule_client_get(&req->rq_pill, &RMF_OBD_IOOBJ);
2587         LASSERT(ioo != NULL);
2588
2589         rnb = req_capsule_client_get(&req->rq_pill, &RMF_NIOBUF_REMOTE);
2590         LASSERT(rnb != NULL);
2591         LASSERT(!(rnb->rnb_flags & OBD_BRW_SRVLOCK));
2592
2593         pa.lpa_mode = LCK_PW | LCK_GROUP;
2594         if (opc == OST_READ)
2595                 pa.lpa_mode |= LCK_PR;
2596
2597         pa.lpa_extent.start = rnb->rnb_offset;
2598         rnb += ioo->ioo_bufcnt - 1;
2599         pa.lpa_extent.end = rnb->rnb_offset + rnb->rnb_len - 1;
2600
2601         DEBUG_REQ(D_RPCTRACE, req,
2602                   "%s %s: refresh rw locks for "DFID" (%llu->%llu)",
2603                   tgt_name(tsi->tsi_tgt), current->comm, PFID(&tsi->tsi_fid),
2604                   pa.lpa_extent.start, pa.lpa_extent.end);
2605
2606         ofd_prolong_extent_locks(tsi, &pa);
2607
2608         CDEBUG(D_DLMTRACE, "%s: refreshed %u locks timeout for req %p\n",
2609                tgt_name(tsi->tsi_tgt), pa.lpa_blocks_cnt, req);
2610
2611         if (pa.lpa_blocks_cnt > 0)
2612                 RETURN(1);
2613
2614         RETURN(pa.lpa_locks_cnt > 0 ? 0 : -ESTALE);
2615 }
2616
2617 /**
2618  * Implementation of ptlrpc_hpreq_ops::hpreq_lock_fini for OFD RW requests.
2619  *
2620  * Called after the request has been handled. It refreshes lock timeout again
2621  * so that client has more time to send lock cancel RPC.
2622  *
2623  * \param[in] req       request which is being processed.
2624  */
2625 static void ofd_rw_hpreq_fini(struct ptlrpc_request *req)
2626 {
2627         ofd_rw_hpreq_check(req);
2628 }
2629
2630 /**
2631  * Implementation of ptlrpc_hpreq_ops::hpreq_lock_match for OST_PUNCH request.
2632  *
2633  * This function checks if the given lock is the same by its resname, mode
2634  * and extent as one taken from the request.
2635  * It is used to give priority to punch/truncate RPCs that might lead to
2636  * the fastest release of that lock when a lock is contended.
2637  *
2638  * \param[in] req       ptlrpc_request being processed
2639  * \param[in] lock      contended lock to match
2640  *
2641  * \retval              1 if lock is matched
2642  * \retval              0 otherwise
2643  */
2644 static int ofd_punch_hpreq_lock_match(struct ptlrpc_request *req,
2645                                       struct ldlm_lock *lock)
2646 {
2647         struct tgt_session_info *tsi;
2648         struct obdo             *oa;
2649         struct ldlm_extent       ext;
2650
2651         ENTRY;
2652
2653         /* Don't use tgt_ses_info() to get session info, because lock_match()
2654          * can be called while request has no processing thread yet. */
2655         tsi = lu_context_key_get(&req->rq_session, &tgt_session_key);
2656
2657         /*
2658          * Use LASSERT below because malformed RPCs should have
2659          * been filtered out in tgt_hpreq_handler().
2660          */
2661         LASSERT(tsi->tsi_ost_body != NULL);
2662         if (tsi->tsi_ost_body->oa.o_valid & OBD_MD_FLHANDLE &&
2663             tsi->tsi_ost_body->oa.o_handle.cookie == lock->l_handle.h_cookie)
2664                 RETURN(1);
2665
2666         oa = &tsi->tsi_ost_body->oa;
2667         ext.start = oa->o_size;
2668         ext.end   = oa->o_blocks;
2669
2670         LASSERT(lock->l_resource != NULL);
2671         if (!ostid_res_name_eq(&oa->o_oi, &lock->l_resource->lr_name))
2672                 RETURN(0);
2673
2674         if (!(lock->l_granted_mode & (LCK_PW | LCK_GROUP)))
2675                 RETURN(0);
2676
2677         RETURN(ldlm_extent_overlap(&lock->l_policy_data.l_extent, &ext));
2678 }
2679
2680 /**
2681  * Implementation of ptlrpc_hpreq_ops::hpreq_lock_check for OST_PUNCH request.
2682  *
2683  * High-priority queue request check for whether the given punch request
2684  * (\a req) is blocking an LDLM lock cancel. Also checks whether the request is
2685  * covered by an LDLM lock.
2686  *
2687
2688  *
2689  * \param[in] req       the incoming request
2690  *
2691  * \retval              1 if \a req is blocking an LDLM lock cancel
2692  * \retval              0 if it is not
2693  * \retval              -ESTALE if lock is not found
2694  */
2695 static int ofd_punch_hpreq_check(struct ptlrpc_request *req)
2696 {
2697         struct tgt_session_info *tsi;
2698         struct obdo             *oa;
2699         struct ldlm_prolong_args pa = { 0 };
2700
2701         ENTRY;
2702
2703         /* Don't use tgt_ses_info() to get session info, because lock_match()
2704          * can be called while request has no processing thread yet. */
2705         tsi = lu_context_key_get(&req->rq_session, &tgt_session_key);
2706         LASSERT(tsi != NULL);
2707         oa = &tsi->tsi_ost_body->oa;
2708
2709         LASSERT(!(oa->o_valid & OBD_MD_FLFLAGS &&
2710                   oa->o_flags & OBD_FL_SRVLOCK));
2711
2712         pa.lpa_mode = LCK_PW | LCK_GROUP;
2713         pa.lpa_extent.start = oa->o_size;
2714         pa.lpa_extent.end   = oa->o_blocks;
2715
2716         CDEBUG(D_DLMTRACE,
2717                "%s: refresh locks: %llu/%llu (%llu->%llu)\n",
2718                tgt_name(tsi->tsi_tgt), tsi->tsi_resid.name[0],
2719                tsi->tsi_resid.name[1], pa.lpa_extent.start, pa.lpa_extent.end);
2720
2721         ofd_prolong_extent_locks(tsi, &pa);
2722
2723         CDEBUG(D_DLMTRACE, "%s: refreshed %u locks timeout for req %p.\n",
2724                tgt_name(tsi->tsi_tgt), pa.lpa_blocks_cnt, req);
2725
2726         if (pa.lpa_blocks_cnt > 0)
2727                 RETURN(1);
2728
2729         RETURN(pa.lpa_locks_cnt > 0 ? 0 : -ESTALE);
2730 }
2731
2732 /**
2733  * Implementation of ptlrpc_hpreq_ops::hpreq_lock_fini for OST_PUNCH request.
2734  *
2735  * Called after the request has been handled. It refreshes lock timeout again
2736  * so that client has more time to send lock cancel RPC.
2737  *
2738  * \param[in] req       request which is being processed.
2739  */
2740 static void ofd_punch_hpreq_fini(struct ptlrpc_request *req)
2741 {
2742         ofd_punch_hpreq_check(req);
2743 }
2744
2745 static struct ptlrpc_hpreq_ops ofd_hpreq_rw = {
2746         .hpreq_lock_match       = ofd_rw_hpreq_lock_match,
2747         .hpreq_check            = ofd_rw_hpreq_check,
2748         .hpreq_fini             = ofd_rw_hpreq_fini
2749 };
2750
2751 static struct ptlrpc_hpreq_ops ofd_hpreq_punch = {
2752         .hpreq_lock_match       = ofd_punch_hpreq_lock_match,
2753         .hpreq_check            = ofd_punch_hpreq_check,
2754         .hpreq_fini             = ofd_punch_hpreq_fini
2755 };
2756
2757 /**
2758  * Assign high priority operations to an IO request.
2759  *
2760  * Check if the incoming request is a candidate for
2761  * high-priority processing. If it is, assign it a high
2762  * priority operations table.
2763  *
2764  * \param[in] tsi       target session environment for this request
2765  */
2766 static void ofd_hp_brw(struct tgt_session_info *tsi)
2767 {
2768         struct niobuf_remote    *rnb;
2769         struct obd_ioobj        *ioo;
2770
2771         ENTRY;
2772
2773         ioo = req_capsule_client_get(tsi->tsi_pill, &RMF_OBD_IOOBJ);
2774         LASSERT(ioo != NULL); /* must exist after request preprocessing */
2775         if (ioo->ioo_bufcnt > 0) {
2776                 rnb = req_capsule_client_get(tsi->tsi_pill, &RMF_NIOBUF_REMOTE);
2777                 LASSERT(rnb != NULL); /* must exist after request preprocessing */
2778
2779                 /* no high priority if server lock is needed */
2780                 if (rnb->rnb_flags & OBD_BRW_SRVLOCK ||
2781                     (lustre_msg_get_flags(tgt_ses_req(tsi)->rq_reqmsg)
2782                      & MSG_REPLAY))
2783                         return;
2784         }
2785         tgt_ses_req(tsi)->rq_ops = &ofd_hpreq_rw;
2786 }
2787
2788 /**
2789  * Assign high priority operations to an punch request.
2790  *
2791  * Check if the incoming request is a candidate for
2792  * high-priority processing. If it is, assign it a high
2793  * priority operations table.
2794  *
2795  * \param[in] tsi       target session environment for this request
2796  */
2797 static void ofd_hp_punch(struct tgt_session_info *tsi)
2798 {
2799         LASSERT(tsi->tsi_ost_body != NULL); /* must exists if we are here */
2800         /* no high-priority if server lock is needed */
2801         if ((tsi->tsi_ost_body->oa.o_valid & OBD_MD_FLFLAGS &&
2802              tsi->tsi_ost_body->oa.o_flags & OBD_FL_SRVLOCK) ||
2803             tgt_conn_flags(tsi) & OBD_CONNECT_MDS ||
2804             lustre_msg_get_flags(tgt_ses_req(tsi)->rq_reqmsg) & MSG_REPLAY)
2805                 return;
2806         tgt_ses_req(tsi)->rq_ops = &ofd_hpreq_punch;
2807 }
2808
2809 #define OBD_FAIL_OST_READ_NET   OBD_FAIL_OST_BRW_NET
2810 #define OBD_FAIL_OST_WRITE_NET  OBD_FAIL_OST_BRW_NET
2811 #define OST_BRW_READ    OST_READ
2812 #define OST_BRW_WRITE   OST_WRITE
2813
2814 /**
2815  * Table of OFD-specific request handlers
2816  *
2817  * This table contains all opcodes accepted by OFD and
2818  * specifies handlers for them. The tgt_request_handler()
2819  * uses such table from each target to process incoming
2820  * requests.
2821  */
2822 static struct tgt_handler ofd_tgt_handlers[] = {
2823 TGT_RPC_HANDLER(OST_FIRST_OPC,
2824                 0,                      OST_CONNECT,    tgt_connect,
2825                 &RQF_CONNECT, LUSTRE_OBD_VERSION),
2826 TGT_RPC_HANDLER(OST_FIRST_OPC,
2827                 0,                      OST_DISCONNECT, tgt_disconnect,
2828                 &RQF_OST_DISCONNECT, LUSTRE_OBD_VERSION),
2829 TGT_RPC_HANDLER(OST_FIRST_OPC,
2830                 0,                      OST_SET_INFO,   ofd_set_info_hdl,
2831                 &RQF_OBD_SET_INFO, LUSTRE_OST_VERSION),
2832 TGT_OST_HDL(0,                          OST_GET_INFO,   ofd_get_info_hdl),
2833 TGT_OST_HDL(HAS_BODY | HAS_REPLY,       OST_GETATTR,    ofd_getattr_hdl),
2834 TGT_OST_HDL(HAS_BODY | HAS_REPLY | IS_MUTABLE,
2835                                         OST_SETATTR,    ofd_setattr_hdl),
2836 TGT_OST_HDL(HAS_REPLY | IS_MUTABLE,
2837                                         OST_CREATE,     ofd_create_hdl),
2838 TGT_OST_HDL(HAS_REPLY | IS_MUTABLE,
2839                                         OST_DESTROY,    ofd_destroy_hdl),
2840 TGT_OST_HDL(HAS_REPLY,  OST_STATFS,     ofd_statfs_hdl),
2841 TGT_OST_HDL_HP(HAS_BODY | HAS_REPLY,    OST_BRW_READ,   tgt_brw_read,
2842                                                         ofd_hp_brw),
2843 /* don't set CORPUS flag for brw_write because -ENOENT may be valid case */
2844 TGT_OST_HDL_HP(HAS_BODY | IS_MUTABLE,   OST_BRW_WRITE,  tgt_brw_write,
2845                                                         ofd_hp_brw),
2846 TGT_OST_HDL_HP(HAS_BODY | HAS_REPLY | IS_MUTABLE,
2847                                         OST_PUNCH,      ofd_punch_hdl,
2848                                                         ofd_hp_punch),
2849 TGT_OST_HDL(HAS_BODY | HAS_REPLY,       OST_SYNC,       ofd_sync_hdl),
2850 TGT_OST_HDL(HAS_REPLY,  OST_QUOTACTL,   ofd_quotactl),
2851 TGT_OST_HDL(HAS_BODY | HAS_REPLY, OST_LADVISE,  ofd_ladvise_hdl),
2852 TGT_OST_HDL(HAS_BODY | HAS_REPLY | IS_MUTABLE, OST_FALLOCATE, ofd_fallocate_hdl),
2853 TGT_OST_HDL(HAS_BODY | HAS_REPLY, OST_SEEK, tgt_lseek),
2854 };
2855
2856 static struct tgt_opc_slice ofd_common_slice[] = {
2857         {
2858                 .tos_opc_start  = OST_FIRST_OPC,
2859                 .tos_opc_end    = OST_LAST_OPC,
2860                 .tos_hs         = ofd_tgt_handlers
2861         },
2862         {
2863                 .tos_opc_start  = OBD_FIRST_OPC,
2864                 .tos_opc_end    = OBD_LAST_OPC,
2865                 .tos_hs         = tgt_obd_handlers
2866         },
2867         {
2868                 .tos_opc_start  = LDLM_FIRST_OPC,
2869                 .tos_opc_end    = LDLM_LAST_OPC,
2870                 .tos_hs         = tgt_dlm_handlers
2871         },
2872         {
2873                 .tos_opc_start  = OUT_UPDATE_FIRST_OPC,
2874                 .tos_opc_end    = OUT_UPDATE_LAST_OPC,
2875                 .tos_hs         = tgt_out_handlers
2876         },
2877         {
2878                 .tos_opc_start  = SEQ_FIRST_OPC,
2879                 .tos_opc_end    = SEQ_LAST_OPC,
2880                 .tos_hs         = seq_handlers
2881         },
2882         {
2883                 .tos_opc_start  = LFSCK_FIRST_OPC,
2884                 .tos_opc_end    = LFSCK_LAST_OPC,
2885                 .tos_hs         = tgt_lfsck_handlers
2886         },
2887         {
2888                 .tos_opc_start  = SEC_FIRST_OPC,
2889                 .tos_opc_end    = SEC_LAST_OPC,
2890                 .tos_hs         = tgt_sec_ctx_handlers
2891         },
2892         {
2893                 .tos_hs         = NULL
2894         }
2895 };
2896
2897 /* context key constructor/destructor: ofd_key_init(), ofd_key_fini() */
2898 LU_KEY_INIT_FINI(ofd, struct ofd_thread_info);
2899
2900 /**
2901  * Implementation of lu_context_key::lct_key_exit.
2902  *
2903  * Optional method called on lu_context_exit() for all allocated
2904  * keys.
2905  * It is used in OFD to sanitize context values which may be re-used
2906  * during another request processing by the same thread.
2907  *
2908  * \param[in] ctx       execution context
2909  * \param[in] key       context key
2910  * \param[in] data      ofd_thread_info
2911  */
2912 static void ofd_key_exit(const struct lu_context *ctx,
2913                          struct lu_context_key *key, void *data)
2914 {
2915         struct ofd_thread_info *info = data;
2916
2917         info->fti_env = NULL;
2918         info->fti_exp = NULL;
2919
2920         info->fti_xid = 0;
2921         info->fti_pre_version = 0;
2922
2923         memset(&info->fti_attr, 0, sizeof info->fti_attr);
2924 }
2925
2926 struct lu_context_key ofd_thread_key = {
2927         .lct_tags = LCT_DT_THREAD,
2928         .lct_init = ofd_key_init,
2929         .lct_fini = ofd_key_fini,
2930         .lct_exit = ofd_key_exit
2931 };
2932
2933 /**
2934  * Initialize OFD device according to parameters in the config log \a cfg.
2935  *
2936  * This is the main starting point of OFD initialization. It fills all OFD
2937  * parameters with their initial values and calls other initializing functions
2938  * to set up all OFD subsystems.
2939  *
2940  * \param[in] env       execution environment
2941  * \param[in] m         OFD device
2942  * \param[in] ldt       LU device type of OFD
2943  * \param[in] cfg       configuration log
2944  *
2945  * \retval              0 if successful
2946  * \retval              negative value on error
2947  */
2948 static int ofd_init0(const struct lu_env *env, struct ofd_device *m,
2949                      struct lu_device_type *ldt, struct lustre_cfg *cfg)
2950 {
2951         const char *dev = lustre_cfg_string(cfg, 0);
2952         struct ofd_thread_info *info = NULL;
2953         struct obd_device *obd;
2954         struct tg_grants_data *tgd = &m->ofd_lut.lut_tgd;
2955         struct lu_fid fid;
2956         struct nm_config_file *nodemap_config;
2957         struct obd_device_target *obt;
2958         u32 lmd_flags = 0;
2959         int rc;
2960
2961         ENTRY;
2962
2963         obd = class_name2obd(dev);
2964         if (obd == NULL) {
2965                 CERROR("Cannot find obd with name %s\n", dev);
2966                 RETURN(-ENODEV);
2967         }
2968
2969         rc = lu_env_refill((struct lu_env *)env);
2970         if (rc != 0)
2971                 RETURN(rc);
2972
2973         obt = &obd->u.obt;
2974         obt->obt_magic = OBT_MAGIC;
2975
2976         spin_lock_init(&m->ofd_flags_lock);
2977         m->ofd_raid_degraded = 0;
2978         m->ofd_sync_journal = 0;
2979         ofd_slc_set(m);
2980         m->ofd_soft_sync_limit = OFD_SOFT_SYNC_LIMIT_DEFAULT;
2981
2982         m->ofd_seq_count = 0;
2983         INIT_LIST_HEAD(&m->ofd_inconsistency_list);
2984         spin_lock_init(&m->ofd_inconsistency_lock);
2985
2986         m->ofd_access_log_mask = -1; /* Log all accesses if enabled. */
2987
2988         spin_lock_init(&m->ofd_batch_lock);
2989         init_rwsem(&m->ofd_lastid_rwsem);
2990
2991         m->ofd_dt_dev.dd_lu_dev.ld_ops = &ofd_lu_ops;
2992         m->ofd_dt_dev.dd_lu_dev.ld_obd = obd;
2993         /* set this lu_device to obd, because error handling need it */
2994         obd->obd_lu_dev = &m->ofd_dt_dev.dd_lu_dev;
2995
2996         /* No connection accepted until configurations will finish */
2997         spin_lock(&obd->obd_dev_lock);
2998         obd->obd_no_conn = 1;
2999         spin_unlock(&obd->obd_dev_lock);
3000         obd->obd_replayable = 1;
3001         if (cfg->lcfg_bufcount > 4 && LUSTRE_CFG_BUFLEN(cfg, 4) > 0) {
3002                 char *str = lustre_cfg_string(cfg, 4);
3003
3004                 if (strchr(str, 'n')) {
3005                         CWARN("%s: recovery disabled\n", obd->obd_name);
3006                         obd->obd_replayable = 0;
3007                 }
3008         }
3009
3010         info = ofd_info_init(env, NULL);
3011         if (info == NULL)
3012                 RETURN(-EFAULT);
3013
3014         rc = ofd_stack_init(env, m, cfg, &lmd_flags);
3015         if (rc) {
3016                 CERROR("%s: can't init device stack, rc %d\n",
3017                        obd->obd_name, rc);
3018                 RETURN(rc);
3019         }
3020
3021 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(2, 14, 53, 0)
3022         ofd_procfs_add_brw_stats_symlink(m);
3023 #endif
3024
3025         snprintf(info->fti_u.name, sizeof(info->fti_u.name), "%s-%s",
3026                  "filter"/*LUSTRE_OST_NAME*/, obd->obd_uuid.uuid);
3027         m->ofd_namespace = ldlm_namespace_new(obd, info->fti_u.name,
3028                                               LDLM_NAMESPACE_SERVER,
3029                                               LDLM_NAMESPACE_GREEDY,
3030                                               LDLM_NS_TYPE_OST);
3031         if (IS_ERR(m->ofd_namespace)) {
3032                 rc = PTR_ERR(m->ofd_namespace);
3033                 CERROR("%s: unable to create server namespace: rc = %d\n",
3034                        obd->obd_name, rc);
3035                 m->ofd_namespace = NULL;
3036                 GOTO(err_fini_stack, rc);
3037         }
3038         /* set obd_namespace for compatibility with old code */
3039         obd->obd_namespace = m->ofd_namespace;
3040         ldlm_register_intent(m->ofd_namespace, ofd_intent_policy);
3041         m->ofd_namespace->ns_lvbo = &ofd_lvbo;
3042         m->ofd_namespace->ns_lvbp = m;
3043
3044         ptlrpc_init_client(LDLM_CB_REQUEST_PORTAL, LDLM_CB_REPLY_PORTAL,
3045                            "filter_ldlm_cb_client", &obd->obd_ldlm_client);
3046
3047         rc = tgt_init(env, &m->ofd_lut, obd, m->ofd_osd, ofd_common_slice,
3048                       OBD_FAIL_OST_ALL_REQUEST_NET,
3049                       OBD_FAIL_OST_ALL_REPLY_NET);
3050         if (rc)
3051                 GOTO(err_free_ns, rc);
3052
3053         if (lmd_flags & LMD_FLG_SKIP_LFSCK)
3054                 m->ofd_skip_lfsck = 1;
3055         if (lmd_flags & LMD_FLG_LOCAL_RECOV)
3056                 m->ofd_lut.lut_local_recovery = 1;
3057
3058         rc = ofd_tunables_init(m);
3059         if (rc)
3060                 GOTO(err_fini_lut, rc);
3061
3062         tgd->tgd_reserved_pcnt = 0;
3063
3064         m->ofd_brw_size = m->ofd_lut.lut_dt_conf.ddp_brw_size;
3065         m->ofd_precreate_batch = OFD_PRECREATE_BATCH_DEFAULT;
3066         if (tgd->tgd_osfs.os_bsize * tgd->tgd_osfs.os_blocks <
3067             OFD_PRECREATE_SMALL_FS)
3068                 m->ofd_precreate_batch = OFD_PRECREATE_BATCH_SMALL;
3069         m->ofd_atime_diff = OFD_DEF_ATIME_DIFF;
3070
3071         rc = ofd_fs_setup(env, m, obd);
3072         if (rc)
3073                 GOTO(err_fini_proc, rc);
3074
3075         fid.f_seq = FID_SEQ_LOCAL_NAME;
3076         fid.f_oid = 1;
3077         fid.f_ver = 0;
3078         rc = local_oid_storage_init(env, m->ofd_osd, &fid,
3079                                     &m->ofd_los);
3080         if (rc != 0)
3081                 GOTO(err_fini_fs, rc);
3082
3083         nodemap_config = nm_config_file_register_tgt(env, m->ofd_osd,
3084                                                      m->ofd_los);
3085         if (IS_ERR(nodemap_config)) {
3086                 rc = PTR_ERR(nodemap_config);
3087                 if (rc != -EROFS)
3088                         GOTO(err_fini_los, rc);
3089         } else {
3090                 obt->obt_nodemap_config_file = nodemap_config;
3091         }
3092
3093         rc = ofd_start_inconsistency_verification_thread(m);
3094         if (rc != 0)
3095                 GOTO(err_fini_nm, rc);
3096
3097         tgt_adapt_sptlrpc_conf(&m->ofd_lut);
3098
3099         RETURN(0);
3100
3101 err_fini_nm:
3102         nm_config_file_deregister_tgt(env, obt->obt_nodemap_config_file);
3103         obt->obt_nodemap_config_file = NULL;
3104 err_fini_los:
3105         local_oid_storage_fini(env, m->ofd_los);
3106         m->ofd_los = NULL;
3107 err_fini_fs:
3108         ofd_fs_cleanup(env, m);
3109 err_fini_proc:
3110         ofd_procfs_fini(m);
3111 err_fini_lut:
3112         tgt_fini(env, &m->ofd_lut);
3113 err_free_ns:
3114         ldlm_namespace_free(m->ofd_namespace, NULL, obd->obd_force);
3115         obd->obd_namespace = m->ofd_namespace = NULL;
3116 err_fini_stack:
3117         ofd_stack_fini(env, m, &m->ofd_osd->dd_lu_dev);
3118         return rc;
3119 }
3120
3121 /**
3122  * Stop the OFD device
3123  *
3124  * This function stops the OFD device and all its subsystems.
3125  * This is the end of OFD lifecycle.
3126  *
3127  * \param[in] env       execution environment
3128  * \param[in] m         OFD device
3129  */
3130 static void ofd_fini(const struct lu_env *env, struct ofd_device *m)
3131 {
3132         struct obd_device       *obd = ofd_obd(m);
3133         struct lu_device        *d   = &m->ofd_dt_dev.dd_lu_dev;
3134         struct lfsck_stop        stop;
3135
3136         stop.ls_status = LS_PAUSED;
3137         stop.ls_flags = 0;
3138         lfsck_stop(env, m->ofd_osd, &stop);
3139         ofd_stack_pre_fini(env, m, &m->ofd_dt_dev.dd_lu_dev);
3140         target_recovery_fini(obd);
3141         if (m->ofd_namespace != NULL)
3142                 ldlm_namespace_free_prior(m->ofd_namespace, NULL,
3143                                           d->ld_obd->obd_force);
3144
3145         obd_exports_barrier(obd);
3146         obd_zombie_barrier();
3147
3148         ofd_procfs_fini(m);
3149         tgt_fini(env, &m->ofd_lut);
3150         ofd_stop_inconsistency_verification_thread(m);
3151         lfsck_degister(env, m->ofd_osd);
3152         ofd_fs_cleanup(env, m);
3153         nm_config_file_deregister_tgt(env, obd->u.obt.obt_nodemap_config_file);
3154         obd->u.obt.obt_nodemap_config_file = NULL;
3155
3156         if (m->ofd_namespace != NULL) {
3157                 ldlm_namespace_free_post(m->ofd_namespace);
3158                 d->ld_obd->obd_namespace = m->ofd_namespace = NULL;
3159         }
3160
3161         ofd_access_log_delete(m->ofd_access_log);
3162         m->ofd_access_log = NULL;
3163
3164         ofd_stack_fini(env, m, &m->ofd_dt_dev.dd_lu_dev);
3165
3166         LASSERT(atomic_read(&d->ld_ref) == 0);
3167         server_put_mount(obd->obd_name, true);
3168         EXIT;
3169 }
3170
3171 /**
3172  * Implementation of lu_device_type_operations::ldto_device_fini.
3173  *
3174  * Finalize device. Dual to ofd_device_init(). It is called from
3175  * obd_precleanup() and stops the current device.
3176  *
3177  * \param[in] env       execution environment
3178  * \param[in] d         LU device of OFD
3179  *
3180  * \retval              NULL
3181  */
3182 static struct lu_device *ofd_device_fini(const struct lu_env *env,
3183                                          struct lu_device *d)
3184 {
3185         ENTRY;
3186         ofd_fini(env, ofd_dev(d));
3187         RETURN(NULL);
3188 }
3189
3190 /**
3191  * Implementation of lu_device_type_operations::ldto_device_free.
3192  *
3193  * Free OFD device. Dual to ofd_device_alloc().
3194  *
3195  * \param[in] env       execution environment
3196  * \param[in] d         LU device of OFD
3197  *
3198  * \retval              NULL
3199  */
3200 static struct lu_device *ofd_device_free(const struct lu_env *env,
3201                                          struct lu_device *d)
3202 {
3203         struct ofd_device *m = ofd_dev(d);
3204
3205         dt_device_fini(&m->ofd_dt_dev);
3206         OBD_FREE_PTR(m);
3207         RETURN(NULL);
3208 }
3209
3210 /**
3211  * Implementation of lu_device_type_operations::ldto_device_alloc.
3212  *
3213  * This function allocates the new OFD device. It is called from
3214  * obd_setup() if OBD device had lu_device_type defined.
3215  *
3216  * \param[in] env       execution environment
3217  * \param[in] t         lu_device_type of OFD device
3218  * \param[in] cfg       configuration log
3219  *
3220  * \retval              pointer to the lu_device of just allocated OFD
3221  * \retval              ERR_PTR of return value on error
3222  */
3223 static struct lu_device *ofd_device_alloc(const struct lu_env *env,
3224                                           struct lu_device_type *t,
3225                                           struct lustre_cfg *cfg)
3226 {
3227         struct ofd_device *m;
3228         struct lu_device  *l;
3229         int                rc;
3230
3231         OBD_ALLOC_PTR(m);
3232         if (m == NULL)
3233                 return ERR_PTR(-ENOMEM);
3234
3235         l = &m->ofd_dt_dev.dd_lu_dev;
3236         dt_device_init(&m->ofd_dt_dev, t);
3237         rc = ofd_init0(env, m, t, cfg);
3238         if (rc != 0) {
3239                 ofd_device_free(env, l);
3240                 l = ERR_PTR(rc);
3241         }
3242
3243         return l;
3244 }
3245
3246 /* type constructor/destructor: ofd_type_init(), ofd_type_fini() */
3247 LU_TYPE_INIT_FINI(ofd, &ofd_thread_key);
3248
3249 static const struct lu_device_type_operations ofd_device_type_ops = {
3250         .ldto_init              = ofd_type_init,
3251         .ldto_fini              = ofd_type_fini,
3252
3253         .ldto_start             = ofd_type_start,
3254         .ldto_stop              = ofd_type_stop,
3255
3256         .ldto_device_alloc      = ofd_device_alloc,
3257         .ldto_device_free       = ofd_device_free,
3258         .ldto_device_fini       = ofd_device_fini
3259 };
3260
3261 static struct lu_device_type ofd_device_type = {
3262         .ldt_tags       = LU_DEVICE_DT,
3263         .ldt_name       = LUSTRE_OST_NAME,
3264         .ldt_ops        = &ofd_device_type_ops,
3265         .ldt_ctx_tags   = LCT_DT_THREAD
3266 };
3267
3268 /**
3269  * Initialize OFD module.
3270  *
3271  * This function is called upon module loading. It registers OFD device type
3272  * and prepares all in-memory structures used by all OFD devices.
3273  *
3274  * \retval              0 if successful
3275  * \retval              negative value on error
3276  */
3277 static int __init ofd_init(void)
3278 {
3279         int rc;
3280
3281         rc = lu_kmem_init(ofd_caches);
3282         if (rc)
3283                 return rc;
3284
3285         rc = ofd_access_log_module_init();
3286         if (rc)
3287                 goto out_caches;
3288
3289         rc = class_register_type(&ofd_obd_ops, NULL, true,
3290                                  LUSTRE_OST_NAME, &ofd_device_type);
3291         if (rc)
3292                 goto out_ofd_access_log;
3293
3294         return 0;
3295
3296 out_ofd_access_log:
3297         ofd_access_log_module_exit();
3298 out_caches:
3299         lu_kmem_fini(ofd_caches);
3300
3301         return rc;
3302 }
3303
3304 /**
3305  * Stop OFD module.
3306  *
3307  * This function is called upon OFD module unloading.
3308  * It frees all related structures and unregisters OFD device type.
3309  */
3310 static void __exit ofd_exit(void)
3311 {
3312         class_unregister_type(LUSTRE_OST_NAME);
3313         ofd_access_log_module_exit();
3314         lu_kmem_fini(ofd_caches);
3315 }
3316
3317 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
3318 MODULE_DESCRIPTION("Lustre Object Filtering Device");
3319 MODULE_VERSION(LUSTRE_VERSION_STRING);
3320 MODULE_LICENSE("GPL");
3321
3322 module_init(ofd_init);
3323 module_exit(ofd_exit);