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