Whamcloud - gitweb
c88eeb1c72eb22f2e4d65177af559c82c28288fe
[fs/lustre-release.git] / lustre / osp / osp_precreate.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2016, 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/osp/osp_sync.c
33  *
34  * Lustre OST Proxy Device
35  *
36  * Author: Alex Zhuravlev <alexey.zhuravlev@intel.com>
37  * Author: Mikhail Pershin <mike.pershin@intel.com>
38  * Author: Di Wang <di.wang@intel.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_MDS
42
43 #include <linux/kthread.h>
44
45 #include <lustre_obdo.h>
46
47 #include "osp_internal.h"
48
49 /*
50  * there are two specific states to take care about:
51  *
52  * = import is disconnected =
53  *
54  * = import is inactive =
55  *   in this case osp_declare_create() returns an error
56  *
57  */
58
59 /*
60  **
61  * Check whether statfs data is expired
62  *
63  * OSP device caches statfs data for the target, the function checks
64  * whether the data is expired or not.
65  *
66  * \param[in] d         OSP device
67  *
68  * \retval              0 - not expired, 1 - expired
69  */
70 static inline int osp_statfs_need_update(struct osp_device *d)
71 {
72         return !cfs_time_before(cfs_time_current(),
73                                 d->opd_statfs_fresh_till);
74 }
75
76 /*
77  * OSP tries to maintain pool of available objects so that calls to create
78  * objects don't block most of time
79  *
80  * each time OSP gets connected to OST, we should start from precreation cleanup
81  */
82 static inline bool osp_precreate_running(struct osp_device *d)
83 {
84         return !!(d->opd_pre_thread.t_flags & SVC_RUNNING);
85 }
86
87 static inline bool osp_precreate_stopped(struct osp_device *d)
88 {
89         return !!(d->opd_pre_thread.t_flags & SVC_STOPPED);
90 }
91
92 static void osp_statfs_timer_cb(unsigned long _d)
93 {
94         struct osp_device *d = (struct osp_device *) _d;
95
96         LASSERT(d);
97         if (d->opd_pre != NULL && osp_precreate_running(d))
98                 wake_up(&d->opd_pre_waitq);
99 }
100
101 /**
102  * RPC interpret callback for OST_STATFS RPC
103  *
104  * An interpretation callback called by ptlrpc for OST_STATFS RPC when it is
105  * replied by the target. It's used to maintain statfs cache for the target.
106  * The function fills data from the reply if successful and schedules another
107  * update.
108  *
109  * \param[in] env       LU environment provided by the caller
110  * \param[in] req       RPC replied
111  * \param[in] aa        callback data
112  * \param[in] rc        RPC result
113  *
114  * \retval 0            on success
115  * \retval negative     negated errno on error
116  */
117 static int osp_statfs_interpret(const struct lu_env *env,
118                                 struct ptlrpc_request *req,
119                                 union ptlrpc_async_args *aa, int rc)
120 {
121         struct obd_import       *imp = req->rq_import;
122         struct obd_statfs       *msfs;
123         struct osp_device       *d;
124
125         ENTRY;
126
127         aa = ptlrpc_req_async_args(req);
128         d = aa->pointer_arg[0];
129         LASSERT(d);
130
131         if (rc != 0)
132                 GOTO(out, rc);
133
134         msfs = req_capsule_server_get(&req->rq_pill, &RMF_OBD_STATFS);
135         if (msfs == NULL)
136                 GOTO(out, rc = -EPROTO);
137
138         d->opd_statfs = *msfs;
139
140         osp_pre_update_status(d, rc);
141
142         /* schedule next update */
143         d->opd_statfs_fresh_till = cfs_time_shift(d->opd_statfs_maxage);
144         mod_timer(&d->opd_statfs_timer, d->opd_statfs_fresh_till);
145         d->opd_statfs_update_in_progress = 0;
146
147         CDEBUG(D_CACHE, "updated statfs %p\n", d);
148
149         RETURN(0);
150 out:
151         /* couldn't update statfs, try again as soon as possible */
152         if (d->opd_pre != NULL && osp_precreate_running(d))
153                 wake_up(&d->opd_pre_waitq);
154
155         if (req->rq_import_generation == imp->imp_generation)
156                 CDEBUG(D_CACHE, "%s: couldn't update statfs: rc = %d\n",
157                        d->opd_obd->obd_name, rc);
158         RETURN(rc);
159 }
160
161 /**
162  * Send OST_STATFS RPC
163  *
164  * Sends OST_STATFS RPC to refresh cached statfs data for the target.
165  * Also disables scheduled updates as times OSP may need to refresh
166  * statfs data before expiration. The function doesn't block, instead
167  * an interpretation callback osp_statfs_interpret() is used.
168  *
169  * \param[in] d         OSP device
170  */
171 static int osp_statfs_update(struct osp_device *d)
172 {
173         struct ptlrpc_request   *req;
174         struct obd_import       *imp;
175         union ptlrpc_async_args *aa;
176         int                      rc;
177
178         ENTRY;
179
180         CDEBUG(D_CACHE, "going to update statfs\n");
181
182         imp = d->opd_obd->u.cli.cl_import;
183         LASSERT(imp);
184
185         req = ptlrpc_request_alloc(imp, &RQF_OST_STATFS);
186         if (req == NULL)
187                 RETURN(-ENOMEM);
188
189         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_STATFS);
190         if (rc) {
191                 ptlrpc_request_free(req);
192                 RETURN(rc);
193         }
194         ptlrpc_request_set_replen(req);
195         req->rq_request_portal = OST_CREATE_PORTAL;
196         ptlrpc_at_set_req_timeout(req);
197
198         req->rq_interpret_reply = (ptlrpc_interpterer_t)osp_statfs_interpret;
199         aa = ptlrpc_req_async_args(req);
200         aa->pointer_arg[0] = d;
201
202         /*
203          * no updates till reply
204          */
205         del_timer(&d->opd_statfs_timer);
206         d->opd_statfs_fresh_till = cfs_time_shift(obd_timeout * 1000);
207         d->opd_statfs_update_in_progress = 1;
208
209         ptlrpcd_add_req(req);
210
211         RETURN(0);
212 }
213
214 /**
215  * Schedule an immediate update for statfs data
216  *
217  * If cached statfs data claim no free space, but OSP has got a request to
218  * destroy an object (so release some space probably), then we may need to
219  * refresh cached statfs data sooner than planned. The function checks there
220  * is no statfs update going and schedules immediate update if so.
221  * XXX: there might be a case where removed object(s) do not add free space (empty
222  * object). If the number of such deletions is high, then we can start to update
223  * statfs too often causing a RPC storm. some throttling is needed...
224  *
225  * \param[in] d         OSP device where statfs data needs to be refreshed
226  */
227 void osp_statfs_need_now(struct osp_device *d)
228 {
229         if (!d->opd_statfs_update_in_progress) {
230                 /*
231                  * if current status is -ENOSPC (lack of free space on OST)
232                  * then we should poll OST immediately once object destroy
233                  * is replied
234                  */
235                 d->opd_statfs_fresh_till = cfs_time_shift(-1);
236                 del_timer(&d->opd_statfs_timer);
237                 wake_up(&d->opd_pre_waitq);
238         }
239 }
240
241 /**
242  * Check pool of precreated objects is nearly empty
243  *
244  * We should not wait till the pool of the precreated objects is exhausted,
245  * because then there will be a long period of OSP being unavailable for the
246  * new creations due to lenghty precreate RPC. Instead we ask for another
247  * precreation ahead and hopefully have it ready before the current pool is
248  * empty. Notice this function relies on an external locking.
249  *
250  * \param[in] env       LU environment provided by the caller
251  * \param[in] d         OSP device
252  *
253  * \retval              0 - current pool is good enough, 1 - time to precreate
254  */
255 static inline int osp_precreate_near_empty_nolock(const struct lu_env *env,
256                                                   struct osp_device *d)
257 {
258         int window = osp_objs_precreated(env, d);
259
260         /* don't consider new precreation till OST is healty and
261          * has free space */
262         return ((window - d->opd_pre_reserved < d->opd_pre_create_count / 2) &&
263                 (d->opd_pre_status == 0));
264 }
265
266 /**
267  * Check pool of precreated objects
268  *
269  * This is protected version of osp_precreate_near_empty_nolock(), check that
270  * for the details.
271  *
272  * \param[in] env       LU environment provided by the caller
273  * \param[in] d         OSP device
274  *
275  * \retval              0 - current pool is good enough, 1 - time to precreate
276  */
277 static inline int osp_precreate_near_empty(const struct lu_env *env,
278                                            struct osp_device *d)
279 {
280         int rc;
281
282         /* XXX: do we really need locking here? */
283         spin_lock(&d->opd_pre_lock);
284         rc = osp_precreate_near_empty_nolock(env, d);
285         spin_unlock(&d->opd_pre_lock);
286         return rc;
287 }
288
289 /**
290  * Check given sequence is empty
291  *
292  * Returns a binary result whether the given sequence has some IDs left
293  * or not. Find the details in osp_fid_end_seq(). This is a lock protected
294  * version of that function.
295  *
296  * \param[in] env       LU environment provided by the caller
297  * \param[in] osp       OSP device
298  *
299  * \retval              0 - current sequence has no IDs, 1 - otherwise
300  */
301 static inline int osp_create_end_seq(const struct lu_env *env,
302                                      struct osp_device *osp)
303 {
304         struct lu_fid *fid = &osp->opd_pre_used_fid;
305         int rc;
306
307         spin_lock(&osp->opd_pre_lock);
308         rc = osp_fid_end_seq(env, fid);
309         spin_unlock(&osp->opd_pre_lock);
310         return rc;
311 }
312
313 /**
314  * Write FID into into last_oid/last_seq file
315  *
316  * The function stores the sequence and the in-sequence id into two dedicated
317  * files. The sync argument can be used to request synchronous commit, so the
318  * function won't return until the updates are committed.
319  *
320  * \param[in] env       LU environment provided by the caller
321  * \param[in] osp       OSP device
322  * \param[in] fid       fid where sequence/id is taken
323  * \param[in] sync      update mode: 0 - asynchronously, 1 - synchronously
324  *
325  * \retval 0            on success
326  * \retval negative     negated errno on error
327  **/
328 int osp_write_last_oid_seq_files(struct lu_env *env, struct osp_device *osp,
329                                  struct lu_fid *fid, int sync)
330 {
331         struct osp_thread_info  *oti = osp_env_info(env);
332         struct lu_buf      *lb_oid = &oti->osi_lb;
333         struct lu_buf      *lb_oseq = &oti->osi_lb2;
334         loff_t             oid_off;
335         loff_t             oseq_off;
336         struct thandle    *th;
337         int                   rc;
338         ENTRY;
339
340         if (osp->opd_storage->dd_rdonly)
341                 RETURN(0);
342
343         /* Note: through f_oid is only 32 bits, it will also write 64 bits
344          * for oid to keep compatibility with the previous version. */
345         lb_oid->lb_buf = &fid->f_oid;
346         lb_oid->lb_len = sizeof(u64);
347         oid_off = sizeof(u64) * osp->opd_index;
348
349         lb_oseq->lb_buf = &fid->f_seq;
350         lb_oseq->lb_len = sizeof(u64);
351         oseq_off = sizeof(u64) * osp->opd_index;
352
353         th = dt_trans_create(env, osp->opd_storage);
354         if (IS_ERR(th))
355                 RETURN(PTR_ERR(th));
356
357         th->th_sync |= sync;
358         rc = dt_declare_record_write(env, osp->opd_last_used_oid_file,
359                                      lb_oid, oid_off, th);
360         if (rc != 0)
361                 GOTO(out, rc);
362
363         rc = dt_declare_record_write(env, osp->opd_last_used_seq_file,
364                                      lb_oseq, oseq_off, th);
365         if (rc != 0)
366                 GOTO(out, rc);
367
368         rc = dt_trans_start_local(env, osp->opd_storage, th);
369         if (rc != 0)
370                 GOTO(out, rc);
371
372         rc = dt_record_write(env, osp->opd_last_used_oid_file, lb_oid,
373                              &oid_off, th);
374         if (rc != 0) {
375                 CERROR("%s: can not write to last seq file: rc = %d\n",
376                         osp->opd_obd->obd_name, rc);
377                 GOTO(out, rc);
378         }
379         rc = dt_record_write(env, osp->opd_last_used_seq_file, lb_oseq,
380                              &oseq_off, th);
381         if (rc) {
382                 CERROR("%s: can not write to last seq file: rc = %d\n",
383                         osp->opd_obd->obd_name, rc);
384                 GOTO(out, rc);
385         }
386 out:
387         dt_trans_stop(env, osp->opd_storage, th);
388         RETURN(rc);
389 }
390
391 /**
392  * Switch to another sequence
393  *
394  * When a current sequence has no available IDs left, OSP has to switch to
395  * another new sequence. OSP requests it using the regular FLDB protocol
396  * and stores synchronously before that is used in precreated. This is needed
397  * to basically have the sequences referenced (not orphaned), otherwise it's
398  * possible that OST has some objects precreated and the clients have data
399  * written to it, but after MDT failover nobody refers those objects and OSP
400  * has no idea that the sequence need cleanup to be done.
401  * While this is very expensive operation, it's supposed to happen very very
402  * infrequently because sequence has 2^32 or 2^48 objects (depending on type)
403  *
404  * \param[in] env       LU environment provided by the caller
405  * \param[in] osp       OSP device
406  *
407  * \retval 0            on success
408  * \retval negative     negated errno on error
409  */
410 static int osp_precreate_rollover_new_seq(struct lu_env *env,
411                                           struct osp_device *osp)
412 {
413         struct lu_fid   *fid = &osp_env_info(env)->osi_fid;
414         struct lu_fid   *last_fid = &osp->opd_last_used_fid;
415         int             rc;
416         ENTRY;
417
418         rc = seq_client_get_seq(env, osp->opd_obd->u.cli.cl_seq, &fid->f_seq);
419         if (rc != 0) {
420                 CERROR("%s: alloc fid error: rc = %d\n",
421                        osp->opd_obd->obd_name, rc);
422                 RETURN(rc);
423         }
424
425         fid->f_oid = 1;
426         fid->f_ver = 0;
427         LASSERTF(fid_seq(fid) != fid_seq(last_fid),
428                  "fid "DFID", last_fid "DFID"\n", PFID(fid),
429                  PFID(last_fid));
430
431         rc = osp_write_last_oid_seq_files(env, osp, fid, 1);
432         if (rc != 0) {
433                 CERROR("%s: Can not update oid/seq file: rc = %d\n",
434                        osp->opd_obd->obd_name, rc);
435                 RETURN(rc);
436         }
437
438         LCONSOLE_INFO("%s: update sequence from %#llx to %#llx\n",
439                       osp->opd_obd->obd_name, fid_seq(last_fid),
440                       fid_seq(fid));
441         /* Update last_xxx to the new seq */
442         spin_lock(&osp->opd_pre_lock);
443         osp->opd_last_used_fid = *fid;
444         osp->opd_gap_start_fid = *fid;
445         osp->opd_pre_used_fid = *fid;
446         osp->opd_pre_last_created_fid = *fid;
447         spin_unlock(&osp->opd_pre_lock);
448
449         RETURN(rc);
450 }
451
452 /**
453  * Find IDs available in current sequence
454  *
455  * The function calculates the highest possible ID and the number of IDs
456  * available in the current sequence OSP is using. The number is limited
457  * artifically by the caller (grow param) and the number of IDs available
458  * in the sequence by nature. The function doesn't require an external
459  * locking.
460  *
461  * \param[in] env       LU environment provided by the caller
462  * \param[in] osp       OSP device
463  * \param[in] fid       FID the caller wants to start with
464  * \param[in] grow      how many the caller wants
465  * \param[out] fid      the highest calculated FID
466  * \param[out] grow     the number of available IDs calculated
467  *
468  * \retval              0 on success, 1 - the sequence is empty
469  */
470 static int osp_precreate_fids(const struct lu_env *env, struct osp_device *osp,
471                               struct lu_fid *fid, int *grow)
472 {
473         struct osp_thread_info  *osi = osp_env_info(env);
474         __u64                   end;
475         int                     i = 0;
476
477         if (fid_is_idif(fid)) {
478                 struct lu_fid   *last_fid;
479                 struct ost_id   *oi = &osi->osi_oi;
480                 int rc;
481
482                 spin_lock(&osp->opd_pre_lock);
483                 last_fid = &osp->opd_pre_last_created_fid;
484                 fid_to_ostid(last_fid, oi);
485                 end = min(ostid_id(oi) + *grow, IDIF_MAX_OID);
486                 *grow = end - ostid_id(oi);
487                 rc = ostid_set_id(oi, ostid_id(oi) + *grow);
488                 spin_unlock(&osp->opd_pre_lock);
489
490                 if (*grow == 0 || rc)
491                         return 1;
492
493                 ostid_to_fid(fid, oi, osp->opd_index);
494                 return 0;
495         }
496
497         spin_lock(&osp->opd_pre_lock);
498         *fid = osp->opd_pre_last_created_fid;
499         end = fid->f_oid;
500         end = min((end + *grow), (__u64)LUSTRE_DATA_SEQ_MAX_WIDTH);
501         *grow = end - fid->f_oid;
502         fid->f_oid += end - fid->f_oid;
503         spin_unlock(&osp->opd_pre_lock);
504
505         CDEBUG(D_INFO, "Expect %d, actual %d ["DFID" -- "DFID"]\n",
506                *grow, i, PFID(fid), PFID(&osp->opd_pre_last_created_fid));
507
508         return *grow > 0 ? 0 : 1;
509 }
510
511 /**
512  * Prepare and send precreate RPC
513  *
514  * The function finds how many objects should be precreated.  Then allocates,
515  * prepares and schedules precreate RPC synchronously. Upon reply the function
516  * wake ups the threads waiting for the new objects on this target. If the
517  * target wasn't able to create all the objects requested, then the next
518  * precreate will be asking less objects (i.e. slow precreate down).
519  *
520  * \param[in] env       LU environment provided by the caller
521  * \param[in] d         OSP device
522  *
523  * \retval 0            on success
524  * \retval negative     negated errno on error
525  **/
526 static int osp_precreate_send(const struct lu_env *env, struct osp_device *d)
527 {
528         struct osp_thread_info  *oti = osp_env_info(env);
529         struct ptlrpc_request   *req;
530         struct obd_import       *imp;
531         struct ost_body         *body;
532         int                      rc, grow, diff;
533         struct lu_fid           *fid = &oti->osi_fid;
534         ENTRY;
535
536         /* don't precreate new objects till OST healthy and has free space */
537         if (unlikely(d->opd_pre_status)) {
538                 CDEBUG(D_INFO, "%s: don't send new precreate: rc = %d\n",
539                        d->opd_obd->obd_name, d->opd_pre_status);
540                 RETURN(0);
541         }
542
543         /*
544          * if not connection/initialization is compeleted, ignore
545          */
546         imp = d->opd_obd->u.cli.cl_import;
547         LASSERT(imp);
548
549         req = ptlrpc_request_alloc(imp, &RQF_OST_CREATE);
550         if (req == NULL)
551                 RETURN(-ENOMEM);
552         req->rq_request_portal = OST_CREATE_PORTAL;
553         /* we should not resend create request - anyway we will have delorphan
554          * and kill these objects */
555         req->rq_no_delay = req->rq_no_resend = 1;
556
557         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_CREATE);
558         if (rc) {
559                 ptlrpc_request_free(req);
560                 RETURN(rc);
561         }
562
563         spin_lock(&d->opd_pre_lock);
564         if (d->opd_pre_create_count > d->opd_pre_max_create_count / 2)
565                 d->opd_pre_create_count = d->opd_pre_max_create_count / 2;
566         grow = d->opd_pre_create_count;
567         spin_unlock(&d->opd_pre_lock);
568
569         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
570         LASSERT(body);
571
572         *fid = d->opd_pre_last_created_fid;
573         rc = osp_precreate_fids(env, d, fid, &grow);
574         if (rc == 1) {
575                 /* Current seq has been used up*/
576                 if (!osp_is_fid_client(d)) {
577                         osp_pre_update_status(d, -ENOSPC);
578                         rc = -ENOSPC;
579                 }
580                 wake_up(&d->opd_pre_waitq);
581                 GOTO(out_req, rc);
582         }
583
584         if (!osp_is_fid_client(d)) {
585                 /* Non-FID client will always send seq 0 because of
586                  * compatiblity */
587                 LASSERTF(fid_is_idif(fid), "Invalid fid "DFID"\n", PFID(fid));
588                 fid->f_seq = 0;
589         }
590
591         fid_to_ostid(fid, &body->oa.o_oi);
592         body->oa.o_valid = OBD_MD_FLGROUP;
593
594         ptlrpc_request_set_replen(req);
595
596         if (OBD_FAIL_CHECK(OBD_FAIL_OSP_FAKE_PRECREATE))
597                 GOTO(ready, rc = 0);
598
599         rc = ptlrpc_queue_wait(req);
600         if (rc) {
601                 CERROR("%s: can't precreate: rc = %d\n", d->opd_obd->obd_name,
602                        rc);
603                 GOTO(out_req, rc);
604         }
605         LASSERT(req->rq_transno == 0);
606
607         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
608         if (body == NULL)
609                 GOTO(out_req, rc = -EPROTO);
610
611         ostid_to_fid(fid, &body->oa.o_oi, d->opd_index);
612
613 ready:
614         if (osp_fid_diff(fid, &d->opd_pre_used_fid) <= 0) {
615                 CERROR("%s: precreate fid "DFID" < local used fid "DFID
616                        ": rc = %d\n", d->opd_obd->obd_name,
617                        PFID(fid), PFID(&d->opd_pre_used_fid), -ESTALE);
618                 GOTO(out_req, rc = -ESTALE);
619         }
620
621         diff = osp_fid_diff(fid, &d->opd_pre_last_created_fid);
622
623         spin_lock(&d->opd_pre_lock);
624         if (diff < grow) {
625                 /* the OST has not managed to create all the
626                  * objects we asked for */
627                 d->opd_pre_create_count = max(diff, OST_MIN_PRECREATE);
628                 d->opd_pre_create_slow = 1;
629         } else {
630                 /* the OST is able to keep up with the work,
631                  * we could consider increasing create_count
632                  * next time if needed */
633                 d->opd_pre_create_slow = 0;
634         }
635
636         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
637         fid_to_ostid(fid, &body->oa.o_oi);
638
639         d->opd_pre_last_created_fid = *fid;
640         spin_unlock(&d->opd_pre_lock);
641
642         CDEBUG(D_HA, "%s: current precreated pool: "DFID"-"DFID"\n",
643                d->opd_obd->obd_name, PFID(&d->opd_pre_used_fid),
644                PFID(&d->opd_pre_last_created_fid));
645 out_req:
646         /* now we can wakeup all users awaiting for objects */
647         osp_pre_update_status(d, rc);
648         wake_up(&d->opd_pre_user_waitq);
649
650         ptlrpc_req_finished(req);
651         RETURN(rc);
652 }
653
654 /**
655  * Get last precreated object from target (OST)
656  *
657  * Sends synchronous RPC to the target (OST) to learn the last precreated
658  * object. This later is used to remove all unused objects (cleanup orphan
659  * procedure). Also, the next object after one we got will be used as a
660  * starting point for the new precreates.
661  *
662  * \param[in] env       LU environment provided by the caller
663  * \param[in] d         OSP device
664  *
665  * \retval 0            on success
666  * \retval negative     negated errno on error
667  **/
668 static int osp_get_lastfid_from_ost(const struct lu_env *env,
669                                     struct osp_device *d)
670 {
671         struct ptlrpc_request   *req = NULL;
672         struct obd_import       *imp;
673         struct lu_fid           *last_fid;
674         char                    *tmp;
675         int                     rc;
676         ENTRY;
677
678         imp = d->opd_obd->u.cli.cl_import;
679         LASSERT(imp);
680
681         req = ptlrpc_request_alloc(imp, &RQF_OST_GET_INFO_LAST_FID);
682         if (req == NULL)
683                 RETURN(-ENOMEM);
684
685         req_capsule_set_size(&req->rq_pill, &RMF_GETINFO_KEY, RCL_CLIENT,
686                              sizeof(KEY_LAST_FID));
687
688         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_GET_INFO);
689         if (rc) {
690                 ptlrpc_request_free(req);
691                 RETURN(rc);
692         }
693
694         tmp = req_capsule_client_get(&req->rq_pill, &RMF_GETINFO_KEY);
695         memcpy(tmp, KEY_LAST_FID, sizeof(KEY_LAST_FID));
696
697         req->rq_no_delay = req->rq_no_resend = 1;
698         last_fid = req_capsule_client_get(&req->rq_pill, &RMF_FID);
699         fid_cpu_to_le(last_fid, &d->opd_last_used_fid);
700
701         ptlrpc_request_set_replen(req);
702
703         rc = ptlrpc_queue_wait(req);
704         if (rc) {
705                 /* bad-bad OST.. let sysadm sort this out */
706                 if (rc == -ENOTSUPP) {
707                         CERROR("%s: server does not support FID: rc = %d\n",
708                                d->opd_obd->obd_name, -ENOTSUPP);
709                 }
710                 ptlrpc_set_import_active(imp, 0);
711                 GOTO(out, rc);
712         }
713
714         last_fid = req_capsule_server_get(&req->rq_pill, &RMF_FID);
715         if (last_fid == NULL) {
716                 CERROR("%s: Got last_fid failed.\n", d->opd_obd->obd_name);
717                 GOTO(out, rc = -EPROTO);
718         }
719
720         if (!fid_is_sane(last_fid)) {
721                 CERROR("%s: Got insane last_fid "DFID"\n",
722                        d->opd_obd->obd_name, PFID(last_fid));
723                 GOTO(out, rc = -EPROTO);
724         }
725
726         /* Only update the last used fid, if the OST has objects for
727          * this sequence, i.e. fid_oid > 0 */
728         if (fid_oid(last_fid) > 0)
729                 d->opd_last_used_fid = *last_fid;
730
731         CDEBUG(D_HA, "%s: Got last_fid "DFID"\n", d->opd_obd->obd_name,
732                PFID(last_fid));
733
734 out:
735         ptlrpc_req_finished(req);
736         RETURN(rc);
737 }
738
739 /**
740  * Cleanup orphans on OST
741  *
742  * This function is called in a contex of a dedicated thread handling
743  * all the precreation suff. The function waits till local recovery
744  * is complete, then identify all the unreferenced objects (orphans)
745  * using the highest ID referenced by a local and the highest object
746  * precreated by the target. The found range is a subject to removal
747  * using specially flagged RPC. During this process OSP is marked
748  * unavailable for new objects.
749  *
750  * \param[in] env       LU environment provided by the caller
751  * \param[in] d         OSP device
752  *
753  * \retval 0            on success
754  * \retval negative     negated errno on error
755  */
756 static int osp_precreate_cleanup_orphans(struct lu_env *env,
757                                          struct osp_device *d)
758 {
759         struct osp_thread_info  *osi = osp_env_info(env);
760         struct lu_fid           *last_fid = &osi->osi_fid;
761         struct lu_fid            tmp;
762         struct ptlrpc_request   *req = NULL;
763         struct obd_import       *imp;
764         struct ost_body         *body;
765         struct l_wait_info       lwi = { 0 };
766         int                      update_status = 0;
767         int                      rc;
768         int                      diff;
769
770         ENTRY;
771
772         /*
773          * wait for local recovery to finish, so we can cleanup orphans
774          * orphans are all objects since "last used" (assigned). we do not
775          * block waiting for all reservations as this can lead to a deadlock
776          * see LU-8972 for the details.
777          */
778         spin_lock(&d->opd_pre_lock);
779         d->opd_pre_recovering = 1;
780         spin_unlock(&d->opd_pre_lock);
781
782         l_wait_event(d->opd_pre_waitq, d->opd_recovery_completed ||
783                      !osp_precreate_running(d) || d->opd_got_disconnected,
784                      &lwi);
785         if (!osp_precreate_running(d) || d->opd_got_disconnected)
786                 GOTO(out, rc = -EAGAIN);
787
788         CDEBUG(D_HA, "%s: going to cleanup orphans since "DFID"\n",
789                d->opd_obd->obd_name, PFID(&d->opd_last_used_fid));
790
791         *last_fid = d->opd_last_used_fid;
792         /* The OSP should already get the valid seq now */
793         LASSERT(!fid_is_zero(last_fid));
794         if (fid_oid(&d->opd_last_used_fid) < 2) {
795                 /* lastfid looks strange... ask OST */
796                 LCONSOLE_WARN("%s: refresh last id\n", d->opd_obd->obd_name);
797                 rc = osp_get_lastfid_from_ost(env, d);
798                 if (rc)
799                         GOTO(out, rc);
800         }
801
802         imp = d->opd_obd->u.cli.cl_import;
803         LASSERT(imp);
804
805         req = ptlrpc_request_alloc(imp, &RQF_OST_CREATE);
806         if (req == NULL)
807                 GOTO(out, rc = -ENOMEM);
808
809         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_CREATE);
810         if (rc) {
811                 ptlrpc_request_free(req);
812                 req = NULL;
813                 GOTO(out, rc);
814         }
815
816         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
817         if (body == NULL)
818                 GOTO(out, rc = -EPROTO);
819
820         body->oa.o_flags = OBD_FL_DELORPHAN;
821         body->oa.o_valid = OBD_MD_FLFLAGS | OBD_MD_FLGROUP;
822
823         /* cleanup objects upto used+reserved as we do not
824          * want to block the orphan cleanup procedure */
825         spin_lock(&d->opd_pre_lock);
826         if (fid_seq(&d->opd_pre_used_fid) != 0) {
827                 tmp = d->opd_pre_used_fid;
828                 tmp.f_oid += d->opd_pre_reserved;
829                 /* shrink current precreate window to let reserved
830                  * already objects be created and block new
831                  * precreations */
832                 d->opd_pre_last_created_fid = tmp;
833         } else {
834                 tmp = d->opd_last_used_fid;
835         }
836         fid_to_ostid(&tmp, &body->oa.o_oi);
837         spin_unlock(&d->opd_pre_lock);
838
839         ptlrpc_request_set_replen(req);
840
841         /* Don't resend the delorphan req */
842         req->rq_no_resend = req->rq_no_delay = 1;
843
844         rc = ptlrpc_queue_wait(req);
845         if (rc) {
846                 update_status = 1;
847                 GOTO(out, rc);
848         }
849
850         body = req_capsule_server_get(&req->rq_pill, &RMF_OST_BODY);
851         if (body == NULL)
852                 GOTO(out, rc = -EPROTO);
853
854         /* OST provides us with id new pool starts from in body->oa.o_id */
855         ostid_to_fid(last_fid, &body->oa.o_oi, d->opd_index);
856
857         CDEBUG(D_HA, "%s: Got last_id "DFID" from OST, last_created "DFID
858                "last_used is "DFID"\n", d->opd_obd->obd_name, PFID(last_fid),
859                PFID(&d->opd_pre_last_created_fid), PFID(&d->opd_last_used_fid));
860 out:
861         if (req)
862                 ptlrpc_req_finished(req);
863
864         /*
865          * If rc is zero, the pre-creation window should have been emptied.
866          * Since waking up the herd would be useless without pre-created
867          * objects, we defer the signal to osp_precreate_send() in that case.
868          */
869         if (rc != 0) {
870                 if (update_status) {
871                         CERROR("%s: cannot cleanup orphans: rc = %d\n",
872                                d->opd_obd->obd_name, rc);
873                         /* we can't proceed from here, OST seem to
874                          * be in a bad shape, better to wait for
875                          * a new instance of the server and repeat
876                          * from the beginning. notify possible waiters
877                          * this OSP isn't quite functional yet */
878                         osp_pre_update_status(d, rc);
879                 } else {
880                         wake_up(&d->opd_pre_user_waitq);
881                 }
882                 GOTO(ret, rc);
883         }
884
885         spin_lock(&d->opd_pre_lock);
886         d->opd_pre_recovering = 0;
887         spin_unlock(&d->opd_pre_lock);
888
889         /* now we wait until all reserved objects are consumed or released,
890          * so that the window doesn't change. otherwise we can get objects
891          * with wrong FIDs */
892         l_wait_event(d->opd_pre_waitq, d->opd_pre_reserved == 0 ||
893                      !osp_precreate_running(d) || d->opd_got_disconnected, &lwi);
894         if (!osp_precreate_running(d))
895                 GOTO(ret, rc = 0);
896
897         spin_lock(&d->opd_pre_lock);
898         diff = osp_fid_diff(&d->opd_last_used_fid, last_fid);
899         if (diff > 0) {
900                 d->opd_pre_create_count = OST_MIN_PRECREATE + diff;
901                 d->opd_pre_last_created_fid = d->opd_last_used_fid;
902         } else {
903                 d->opd_pre_create_count = OST_MIN_PRECREATE;
904                 d->opd_pre_last_created_fid = *last_fid;
905         }
906         /*
907          * This empties the pre-creation pool and effectively blocks any new
908          * reservations.
909          */
910         LASSERT(fid_oid(&d->opd_pre_last_created_fid) <=
911                         LUSTRE_DATA_SEQ_MAX_WIDTH);
912         d->opd_pre_used_fid = d->opd_pre_last_created_fid;
913         d->opd_pre_create_slow = 0;
914         spin_unlock(&d->opd_pre_lock);
915
916 ret:
917         RETURN(rc);
918 }
919
920 /**
921  * Update precreate status using statfs data
922  *
923  * The function decides whether this OSP should be used for new objects.
924  * IOW, whether this OST is used up or has some free space. Cached statfs
925  * data is used to make this decision. If the latest result of statfs
926  * request (rc argument) is not success, then just mark OSP unavailable
927  * right away.
928
929  * Add a bit of hysteresis so this flag isn't continually flapping,
930  * and ensure that new files don't get extremely fragmented due to
931  * only a small amount of available space in the filesystem.
932  * We want to set the ENOSPC when there is less than reserved size
933  * free and clear it when there is at least 2*reserved size free space.
934  * the function updates current precreation status used: functional or not
935  *
936  * \param[in] d         OSP device
937  * \param[in] rc        new precreate status for device \a d
938  *
939  * \retval 0            on success
940  * \retval negative     negated errno on error
941  */
942 void osp_pre_update_status(struct osp_device *d, int rc)
943 {
944         struct obd_statfs       *msfs = &d->opd_statfs;
945         int                      old = d->opd_pre_status;
946         __u64                    available;
947
948         d->opd_pre_status = rc;
949         if (rc)
950                 goto out;
951
952         if (likely(msfs->os_type)) {
953                 if (unlikely(d->opd_reserved_mb_high == 0 &&
954                              d->opd_reserved_mb_low == 0)) {
955                         /* Use ~0.1% by default to disable object allocation,
956                          * and ~0.2% to enable, size in MB, set both watermark
957                          */
958                         spin_lock(&d->opd_pre_lock);
959                         if (d->opd_reserved_mb_high == 0 &&
960                             d->opd_reserved_mb_low == 0) {
961                                 d->opd_reserved_mb_low =
962                                         ((msfs->os_bsize >> 10) *
963                                         msfs->os_blocks) >> 20;
964                                 if (d->opd_reserved_mb_low == 0)
965                                         d->opd_reserved_mb_low = 1;
966                                 d->opd_reserved_mb_high =
967                                         (d->opd_reserved_mb_low << 1) + 1;
968                         }
969                         spin_unlock(&d->opd_pre_lock);
970                 }
971                 /* in MB */
972                 available = (msfs->os_bavail * (msfs->os_bsize >> 10)) >> 10;
973                 if (msfs->os_ffree < 32)
974                         msfs->os_state |= OS_STATE_ENOINO;
975                 else if (msfs->os_ffree > 64)
976                         msfs->os_state &= ~OS_STATE_ENOINO;
977
978                 if (available < d->opd_reserved_mb_low)
979                         msfs->os_state |= OS_STATE_ENOSPC;
980                 else if (available > d->opd_reserved_mb_high)
981                         msfs->os_state &= ~OS_STATE_ENOSPC;
982                 if (msfs->os_state & (OS_STATE_ENOINO | OS_STATE_ENOSPC)) {
983                         d->opd_pre_status = -ENOSPC;
984                         if (old != -ENOSPC)
985                                 CDEBUG(D_INFO, "%s: status: %llu blocks, %llu "
986                                        "free, %llu avail, %llu MB avail, %u "
987                                        "hwm -> %d: rc = %d\n",
988                                        d->opd_obd->obd_name, msfs->os_blocks,
989                                        msfs->os_bfree, msfs->os_bavail,
990                                        available, d->opd_reserved_mb_high,
991                                        d->opd_pre_status, rc);
992                         CDEBUG(D_INFO,
993                                "non-committed changes: %u, in progress: %u\n",
994                                atomic_read(&d->opd_sync_changes),
995                                atomic_read(&d->opd_sync_rpcs_in_progress));
996                 } else if (unlikely(old == -ENOSPC)) {
997                         d->opd_pre_status = 0;
998                         spin_lock(&d->opd_pre_lock);
999                         d->opd_pre_create_slow = 0;
1000                         d->opd_pre_create_count = OST_MIN_PRECREATE;
1001                         spin_unlock(&d->opd_pre_lock);
1002                         wake_up(&d->opd_pre_waitq);
1003
1004                         CDEBUG(D_INFO, "%s: space available: %llu blocks, %llu"
1005                                " free, %llu avail, %lluMB avail, %u lwm"
1006                                " -> %d: rc = %d\n", d->opd_obd->obd_name,
1007                                msfs->os_blocks, msfs->os_bfree, msfs->os_bavail,
1008                                available, d->opd_reserved_mb_low,
1009                                d->opd_pre_status, rc);
1010                 }
1011         }
1012 out:
1013         wake_up(&d->opd_pre_user_waitq);
1014 }
1015
1016 /**
1017  * Initialize FID for precreation
1018  *
1019  * For a just created new target, a new sequence should be taken.
1020  * The function checks there is no IDIF in use (if the target was
1021  * added with the older version of Lustre), then requests a new
1022  * sequence from FLDB using the regular protocol. Then this new
1023  * sequence is stored on a persisten storage synchronously to prevent
1024  * possible object leakage (for the detail see the description for
1025  * osp_precreate_rollover_new_seq()).
1026  *
1027  * \param[in] osp       OSP device
1028  *
1029  * \retval 0            on success
1030  * \retval negative     negated errno on error
1031  */
1032 int osp_init_pre_fid(struct osp_device *osp)
1033 {
1034         struct lu_env           env;
1035         struct osp_thread_info  *osi;
1036         struct lu_client_seq    *cli_seq;
1037         struct lu_fid           *last_fid;
1038         int                     rc;
1039         ENTRY;
1040
1041         LASSERT(osp->opd_pre != NULL);
1042
1043         /* Let's check if the current last_seq/fid is valid,
1044          * otherwise request new sequence from the controller */
1045         if (osp_is_fid_client(osp) && osp->opd_group != 0) {
1046                 /* Non-MDT0 can only use normal sequence for
1047                  * OST objects */
1048                 if (fid_is_norm(&osp->opd_last_used_fid))
1049                         RETURN(0);
1050         } else {
1051                 /* Initially MDT0 will start with IDIF, after
1052                  * that it will request new sequence from the
1053                  * controller */
1054                 if (fid_is_idif(&osp->opd_last_used_fid) ||
1055                     fid_is_norm(&osp->opd_last_used_fid))
1056                         RETURN(0);
1057         }
1058
1059         if (!fid_is_zero(&osp->opd_last_used_fid))
1060                 CWARN("%s: invalid last used fid "DFID
1061                       ", try to get new sequence.\n",
1062                       osp->opd_obd->obd_name,
1063                       PFID(&osp->opd_last_used_fid));
1064
1065         rc = lu_env_init(&env, osp->opd_dt_dev.dd_lu_dev.ld_type->ldt_ctx_tags);
1066         if (rc) {
1067                 CERROR("%s: init env error: rc = %d\n",
1068                        osp->opd_obd->obd_name, rc);
1069                 RETURN(rc);
1070         }
1071
1072         osi = osp_env_info(&env);
1073         last_fid = &osi->osi_fid;
1074         fid_zero(last_fid);
1075         /* For a freshed fs, it will allocate a new sequence first */
1076         if (osp_is_fid_client(osp) && osp->opd_group != 0) {
1077                 cli_seq = osp->opd_obd->u.cli.cl_seq;
1078                 rc = seq_client_get_seq(&env, cli_seq, &last_fid->f_seq);
1079                 if (rc != 0) {
1080                         CERROR("%s: alloc fid error: rc = %d\n",
1081                                osp->opd_obd->obd_name, rc);
1082                         GOTO(out, rc);
1083                 }
1084         } else {
1085                 last_fid->f_seq = fid_idif_seq(0, osp->opd_index);
1086         }
1087         last_fid->f_oid = 1;
1088         last_fid->f_ver = 0;
1089
1090         spin_lock(&osp->opd_pre_lock);
1091         osp->opd_last_used_fid = *last_fid;
1092         osp->opd_pre_used_fid = *last_fid;
1093         osp->opd_pre_last_created_fid = *last_fid;
1094         spin_unlock(&osp->opd_pre_lock);
1095         rc = osp_write_last_oid_seq_files(&env, osp, last_fid, 1);
1096         if (rc != 0) {
1097                 CERROR("%s: write fid error: rc = %d\n",
1098                        osp->opd_obd->obd_name, rc);
1099                 GOTO(out, rc);
1100         }
1101 out:
1102         lu_env_fini(&env);
1103         RETURN(rc);
1104 }
1105
1106 /**
1107  * The core of precreate functionality
1108  *
1109  * The function implements the main precreation loop. Basically it
1110  * involves connecting to the target, precerate FID initialization,
1111  * identifying and removing orphans, then serving precreation. As
1112  * part of the latter, the thread is responsible for statfs data
1113  * updates. The precreation is mostly driven by another threads
1114  * asking for new OST objects - those askers wake the thread when
1115  * the number of precreated objects reach low watermark.
1116  * After a disconnect, the sequence above repeats. This is keep going
1117  * until the thread is requested to stop.
1118  *
1119  * \param[in] _arg      private data the thread (OSP device to handle)
1120  *
1121  * \retval 0            on success
1122  * \retval negative     negated errno on error
1123  */
1124 static int osp_precreate_thread(void *_arg)
1125 {
1126         struct osp_device       *d = _arg;
1127         struct ptlrpc_thread    *thread = &d->opd_pre_thread;
1128         struct l_wait_info       lwi = { 0 };
1129         struct l_wait_info       lwi2 = LWI_TIMEOUT(cfs_time_seconds(5),
1130                                                     back_to_sleep, NULL);
1131         struct lu_env            env;
1132         int                      rc;
1133
1134         ENTRY;
1135
1136         rc = lu_env_init(&env, d->opd_dt_dev.dd_lu_dev.ld_type->ldt_ctx_tags);
1137         if (rc) {
1138                 CERROR("%s: init env error: rc = %d\n", d->opd_obd->obd_name,
1139                        rc);
1140
1141                 spin_lock(&d->opd_pre_lock);
1142                 thread->t_flags = SVC_STOPPED;
1143                 spin_unlock(&d->opd_pre_lock);
1144                 wake_up(&thread->t_ctl_waitq);
1145
1146                 RETURN(rc);
1147         }
1148
1149         spin_lock(&d->opd_pre_lock);
1150         thread->t_flags = SVC_RUNNING;
1151         spin_unlock(&d->opd_pre_lock);
1152         wake_up(&thread->t_ctl_waitq);
1153
1154         while (osp_precreate_running(d)) {
1155                 /*
1156                  * need to be connected to OST
1157                  */
1158                 while (osp_precreate_running(d)) {
1159                         if (d->opd_pre_recovering &&
1160                             d->opd_imp_connected &&
1161                             !d->opd_got_disconnected)
1162                                 break;
1163                         l_wait_event(d->opd_pre_waitq,
1164                                      !osp_precreate_running(d) ||
1165                                      d->opd_new_connection,
1166                                      &lwi);
1167
1168                         if (!d->opd_new_connection)
1169                                 continue;
1170
1171                         d->opd_new_connection = 0;
1172                         d->opd_got_disconnected = 0;
1173                         break;
1174                 }
1175
1176                 if (!osp_precreate_running(d))
1177                         break;
1178
1179                 LASSERT(d->opd_obd->u.cli.cl_seq != NULL);
1180                 /* Sigh, fid client is not ready yet */
1181                 if (d->opd_obd->u.cli.cl_seq->lcs_exp == NULL)
1182                         continue;
1183
1184                 /* Init fid for osp_precreate if necessary */
1185                 rc = osp_init_pre_fid(d);
1186                 if (rc != 0) {
1187                         class_export_put(d->opd_exp);
1188                         d->opd_obd->u.cli.cl_seq->lcs_exp = NULL;
1189                         CERROR("%s: init pre fid error: rc = %d\n",
1190                                d->opd_obd->obd_name, rc);
1191                         continue;
1192                 }
1193
1194                 if (osp_statfs_update(d)) {
1195                         l_wait_event(d->opd_pre_waitq,
1196                                      !osp_precreate_running(d), &lwi2);
1197                         continue;
1198                 }
1199
1200                 /*
1201                  * Clean up orphans or recreate missing objects.
1202                  */
1203                 rc = osp_precreate_cleanup_orphans(&env, d);
1204                 if (rc != 0) {
1205                         schedule_timeout_interruptible(cfs_time_seconds(1));
1206                         continue;
1207                 }
1208                 /*
1209                  * connected, can handle precreates now
1210                  */
1211                 while (osp_precreate_running(d)) {
1212                         l_wait_event(d->opd_pre_waitq,
1213                                      !osp_precreate_running(d) ||
1214                                      osp_precreate_near_empty(&env, d) ||
1215                                      osp_statfs_need_update(d) ||
1216                                      d->opd_got_disconnected, &lwi);
1217
1218                         if (!osp_precreate_running(d))
1219                                 break;
1220
1221                         /* something happened to the connection
1222                          * have to start from the beginning */
1223                         if (d->opd_got_disconnected)
1224                                 break;
1225
1226                         if (osp_statfs_need_update(d))
1227                                 if (osp_statfs_update(d))
1228                                         break;
1229
1230                         /* To avoid handling different seq in precreate/orphan
1231                          * cleanup, it will hold precreate until current seq is
1232                          * used up. */
1233                         if (unlikely(osp_precreate_end_seq(&env, d) &&
1234                             !osp_create_end_seq(&env, d)))
1235                                 continue;
1236
1237                         if (unlikely(osp_precreate_end_seq(&env, d) &&
1238                                      osp_create_end_seq(&env, d))) {
1239                                 LCONSOLE_INFO("%s:%#llx is used up."
1240                                               " Update to new seq\n",
1241                                               d->opd_obd->obd_name,
1242                                          fid_seq(&d->opd_pre_last_created_fid));
1243                                 rc = osp_precreate_rollover_new_seq(&env, d);
1244                                 if (rc)
1245                                         continue;
1246                         }
1247
1248                         if (osp_precreate_near_empty(&env, d)) {
1249                                 rc = osp_precreate_send(&env, d);
1250                                 /* osp_precreate_send() sets opd_pre_status
1251                                  * in case of error, that prevent the using of
1252                                  * failed device. */
1253                                 if (rc < 0 && rc != -ENOSPC &&
1254                                     rc != -ETIMEDOUT && rc != -ENOTCONN)
1255                                         CERROR("%s: cannot precreate objects:"
1256                                                " rc = %d\n",
1257                                                d->opd_obd->obd_name, rc);
1258                         }
1259                 }
1260         }
1261
1262         thread->t_flags = SVC_STOPPED;
1263         lu_env_fini(&env);
1264         wake_up(&thread->t_ctl_waitq);
1265
1266         RETURN(0);
1267 }
1268
1269 /**
1270  * Check when to stop to wait for precreate objects.
1271  *
1272  * The caller wanting a new OST object can't wait undefinitely. The
1273  * function checks for few conditions including available new OST
1274  * objects, disconnected OST, lack of space with no pending destroys,
1275  * etc. IOW, it checks whether the current OSP state is good to keep
1276  * waiting or it's better to give up.
1277  *
1278  * \param[in] env       LU environment provided by the caller
1279  * \param[in] d         OSP device
1280  *
1281  * \retval              0 - keep waiting, 1 - no luck
1282  */
1283 static int osp_precreate_ready_condition(const struct lu_env *env,
1284                                          struct osp_device *d)
1285 {
1286         if (d->opd_pre_recovering)
1287                 return 0;
1288
1289         /* ready if got enough precreated objects */
1290         /* we need to wait for others (opd_pre_reserved) and our object (+1) */
1291         if (d->opd_pre_reserved + 1 < osp_objs_precreated(env, d))
1292                 return 1;
1293
1294         /* ready if OST reported no space and no destroys in progress */
1295         if (atomic_read(&d->opd_sync_changes) +
1296             atomic_read(&d->opd_sync_rpcs_in_progress) == 0 &&
1297             d->opd_pre_status == -ENOSPC)
1298                 return 1;
1299
1300         /* Bail out I/O fails to OST */
1301         if (d->opd_pre_status != 0 &&
1302             d->opd_pre_status != -EAGAIN &&
1303             d->opd_pre_status != -ENODEV &&
1304             d->opd_pre_status != -ENOTCONN &&
1305             d->opd_pre_status != -ENOSPC) {
1306                 /* DEBUG LU-3230 */
1307                 if (d->opd_pre_status != -EIO)
1308                         CERROR("%s: precreate failed opd_pre_status %d\n",
1309                                d->opd_obd->obd_name, d->opd_pre_status);
1310                 return 1;
1311         }
1312
1313         return 0;
1314 }
1315
1316 static int osp_precreate_timeout_condition(void *data)
1317 {
1318         struct osp_device *d = data;
1319
1320         CDEBUG(D_HA, "%s: slow creates, last="DFID", next="DFID", "
1321               "reserved=%llu, sync_changes=%u, "
1322               "sync_rpcs_in_progress=%d, status=%d\n",
1323               d->opd_obd->obd_name, PFID(&d->opd_pre_last_created_fid),
1324               PFID(&d->opd_pre_used_fid), d->opd_pre_reserved,
1325               atomic_read(&d->opd_sync_changes),
1326               atomic_read(&d->opd_sync_rpcs_in_progress),
1327               d->opd_pre_status);
1328
1329         return 1;
1330 }
1331
1332 /**
1333  * Reserve object in precreate pool
1334  *
1335  * When the caller wants to create a new object on this target (target
1336  * represented by the given OSP), it should declare this intention using
1337  * a regular ->dt_declare_create() OSD API method. Then OSP will be trying
1338  * to reserve an object in the existing precreated pool or wait up to
1339  * obd_timeout for the available object to appear in the pool (a dedicated
1340  * thread will be doing real precreation in background). The object can be
1341  * consumed later with osp_precreate_get_fid() or be released with call to
1342  * lu_object_put(). Notice the function doesn't reserve a specific ID, just
1343  * some ID. The actual ID assignment happen in osp_precreate_get_fid().
1344  * If the space on the target is short and there is a pending object destroy,
1345  * then the function forces local commit to speedup space release (see
1346  * osp_sync.c for the details).
1347  *
1348  * \param[in] env       LU environment provided by the caller
1349  * \param[in] d         OSP device
1350  *
1351  * \retval              0 on success
1352  * \retval              -ENOSPC when no space on OST
1353  * \retval              -EAGAIN try later, slow precreation in progress
1354  * \retval              -EIO when no access to OST
1355  */
1356 int osp_precreate_reserve(const struct lu_env *env, struct osp_device *d)
1357 {
1358         struct l_wait_info       lwi;
1359         cfs_time_t               expire = cfs_time_shift(obd_timeout);
1360         int                      precreated, rc;
1361
1362         ENTRY;
1363
1364         LASSERTF(osp_objs_precreated(env, d) >= 0, "Last created FID "DFID
1365                  "Next FID "DFID"\n", PFID(&d->opd_pre_last_created_fid),
1366                  PFID(&d->opd_pre_used_fid));
1367
1368         /* opd_pre_max_create_count 0 to not use specified OST. */
1369         if (d->opd_pre_max_create_count == 0)
1370                 RETURN(-ENOBUFS);
1371
1372         if (OBD_FAIL_PRECHECK(OBD_FAIL_MDS_OSP_PRECREATE_WAIT)) {
1373                 if (d->opd_index == cfs_fail_val)
1374                         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_OSP_PRECREATE_WAIT,
1375                                          obd_timeout);
1376         }
1377
1378         /*
1379          * wait till:
1380          *  - preallocation is done
1381          *  - no free space expected soon
1382          *  - can't connect to OST for too long (obd_timeout)
1383          *  - OST can allocate fid sequence.
1384          */
1385         while ((rc = d->opd_pre_status) == 0 || rc == -ENOSPC ||
1386                 rc == -ENODEV || rc == -EAGAIN || rc == -ENOTCONN) {
1387
1388                 /*
1389                  * increase number of precreations
1390                  */
1391                 precreated = osp_objs_precreated(env, d);
1392                 if (d->opd_pre_create_count < d->opd_pre_max_create_count &&
1393                     d->opd_pre_create_slow == 0 &&
1394                     precreated <= (d->opd_pre_create_count / 4 + 1)) {
1395                         spin_lock(&d->opd_pre_lock);
1396                         d->opd_pre_create_slow = 1;
1397                         d->opd_pre_create_count *= 2;
1398                         spin_unlock(&d->opd_pre_lock);
1399                 }
1400
1401                 spin_lock(&d->opd_pre_lock);
1402                 precreated = osp_objs_precreated(env, d);
1403                 if (precreated > d->opd_pre_reserved &&
1404                     !d->opd_pre_recovering) {
1405                         d->opd_pre_reserved++;
1406                         spin_unlock(&d->opd_pre_lock);
1407                         rc = 0;
1408
1409                         /* XXX: don't wake up if precreation is in progress */
1410                         if (osp_precreate_near_empty_nolock(env, d) &&
1411                            !osp_precreate_end_seq_nolock(env, d))
1412                                 wake_up(&d->opd_pre_waitq);
1413
1414                         break;
1415                 }
1416                 spin_unlock(&d->opd_pre_lock);
1417
1418                 /*
1419                  * all precreated objects have been used and no-space
1420                  * status leave us no chance to succeed very soon
1421                  * but if there is destroy in progress, then we should
1422                  * wait till that is done - some space might be released
1423                  */
1424                 if (unlikely(rc == -ENOSPC)) {
1425                         if (atomic_read(&d->opd_sync_changes)) {
1426                                 /* force local commit to release space */
1427                                 dt_commit_async(env, d->opd_storage);
1428                         }
1429                         if (atomic_read(&d->opd_sync_rpcs_in_progress)) {
1430                                 /* just wait till destroys are done */
1431                                 /* see l_wait_even() few lines below */
1432                         }
1433                         if (atomic_read(&d->opd_sync_changes) +
1434                             atomic_read(&d->opd_sync_rpcs_in_progress) == 0) {
1435                                 /* no hope for free space */
1436                                 break;
1437                         }
1438                 }
1439
1440                 /* XXX: don't wake up if precreation is in progress */
1441                 wake_up(&d->opd_pre_waitq);
1442
1443                 lwi = LWI_TIMEOUT(expire - cfs_time_current(),
1444                                 osp_precreate_timeout_condition, d);
1445                 if (cfs_time_aftereq(cfs_time_current(), expire)) {
1446                         rc = -ETIMEDOUT;
1447                         break;
1448                 }
1449
1450                 l_wait_event(d->opd_pre_user_waitq,
1451                              osp_precreate_ready_condition(env, d), &lwi);
1452         }
1453
1454         RETURN(rc);
1455 }
1456
1457 /**
1458  * Get a FID from precreation pool
1459  *
1460  * The function is a companion for osp_precreate_reserve() - it assigns
1461  * a specific FID from the precreate. The function should be called only
1462  * if the call to osp_precreate_reserve() was successful. The function
1463  * updates a local storage to remember the highest object ID referenced
1464  * by the node in the given sequence.
1465  *
1466  * A very importan details: this is supposed to be called once the
1467  * transaction is started, so on-disk update will be atomic with the
1468  * data (like LOVEA) refering this object. Then the object won't be leaked:
1469  * either it's referenced by the committed transaction or it's a subject
1470  * to the orphan cleanup procedure.
1471  *
1472  * \param[in] env       LU environment provided by the caller
1473  * \param[in] d         OSP device
1474  * \param[out] fid      generated FID
1475  *
1476  * \retval 0            on success
1477  * \retval negative     negated errno on error
1478  */
1479 int osp_precreate_get_fid(const struct lu_env *env, struct osp_device *d,
1480                           struct lu_fid *fid)
1481 {
1482         /* grab next id from the pool */
1483         spin_lock(&d->opd_pre_lock);
1484
1485         LASSERTF(osp_fid_diff(&d->opd_pre_used_fid,
1486                              &d->opd_pre_last_created_fid) < 0,
1487                  "next fid "DFID" last created fid "DFID"\n",
1488                  PFID(&d->opd_pre_used_fid),
1489                  PFID(&d->opd_pre_last_created_fid));
1490
1491         d->opd_pre_used_fid.f_oid++;
1492         memcpy(fid, &d->opd_pre_used_fid, sizeof(*fid));
1493         d->opd_pre_reserved--;
1494         /*
1495          * last_used_id must be changed along with getting new id otherwise
1496          * we might miscalculate gap causing object loss or leak
1497          */
1498         osp_update_last_fid(d, fid);
1499         spin_unlock(&d->opd_pre_lock);
1500
1501         /*
1502          * probably main thread suspended orphan cleanup till
1503          * all reservations are released, see comment in
1504          * osp_precreate_thread() just before orphan cleanup
1505          */
1506         if (unlikely(d->opd_pre_reserved == 0 && d->opd_pre_status))
1507                 wake_up(&d->opd_pre_waitq);
1508
1509         return 0;
1510 }
1511
1512 /*
1513  * Set size regular attribute on an object
1514  *
1515  * When a striping is created late, it's possible that size is already
1516  * initialized on the file. Then the new striping should inherit size
1517  * from the file. The function sets size on the object using the regular
1518  * protocol (OST_PUNCH).
1519  * XXX: should be re-implemented using OUT ?
1520  *
1521  * \param[in] env       LU environment provided by the caller
1522  * \param[in] dt        object
1523  * \param[in] size      size to set.
1524  *
1525  * \retval 0            on success
1526  * \retval negative     negated errno on error
1527  */
1528 int osp_object_truncate(const struct lu_env *env, struct dt_object *dt,
1529                         __u64 size)
1530 {
1531         struct osp_device       *d = lu2osp_dev(dt->do_lu.lo_dev);
1532         struct ptlrpc_request   *req = NULL;
1533         struct obd_import       *imp;
1534         struct ost_body         *body;
1535         struct obdo             *oa = NULL;
1536         int                      rc;
1537
1538         ENTRY;
1539
1540         imp = d->opd_obd->u.cli.cl_import;
1541         LASSERT(imp);
1542
1543         req = ptlrpc_request_alloc(imp, &RQF_OST_PUNCH);
1544         if (req == NULL)
1545                 RETURN(-ENOMEM);
1546
1547         /* XXX: capa support? */
1548         /* osc_set_capa_size(req, &RMF_CAPA1, capa); */
1549         rc = ptlrpc_request_pack(req, LUSTRE_OST_VERSION, OST_PUNCH);
1550         if (rc) {
1551                 ptlrpc_request_free(req);
1552                 RETURN(rc);
1553         }
1554
1555         /*
1556          * XXX: decide how do we do here with resend
1557          * if we don't resend, then client may see wrong file size
1558          * if we do resend, then MDS thread can get stuck for quite long
1559          * and if we don't resend, then client will also get -EWOULDBLOCK !!
1560          * (see LU-7975 and sanity/test_27F use cases)
1561          * but let's decide not to resend/delay this truncate request to OST
1562          * and allow Client to decide to resend, in a less agressive way from
1563          * after_reply(), by returning -EINPROGRESS instead of
1564          * -EAGAIN/-EWOULDBLOCK upon return from ptlrpc_queue_wait() at the
1565          * end of this routine
1566          */
1567         req->rq_no_resend = req->rq_no_delay = 1;
1568
1569         req->rq_request_portal = OST_IO_PORTAL; /* bug 7198 */
1570         ptlrpc_at_set_req_timeout(req);
1571
1572         OBD_ALLOC_PTR(oa);
1573         if (oa == NULL)
1574                 GOTO(out, rc = -ENOMEM);
1575
1576         rc = fid_to_ostid(lu_object_fid(&dt->do_lu), &oa->o_oi);
1577         LASSERT(rc == 0);
1578         oa->o_size = size;
1579         oa->o_blocks = OBD_OBJECT_EOF;
1580         oa->o_valid = OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
1581                       OBD_MD_FLID | OBD_MD_FLGROUP;
1582
1583         body = req_capsule_client_get(&req->rq_pill, &RMF_OST_BODY);
1584         LASSERT(body);
1585         lustre_set_wire_obdo(&req->rq_import->imp_connect_data, &body->oa, oa);
1586
1587         /* XXX: capa support? */
1588         /* osc_pack_capa(req, body, capa); */
1589
1590         ptlrpc_request_set_replen(req);
1591
1592         rc = ptlrpc_queue_wait(req);
1593         if (rc) {
1594                 /* -EWOULDBLOCK/-EAGAIN means OST is unreachable at the moment
1595                  * since we have decided not to resend/delay, but this could
1596                  * lead to wrong size to be seen at Client side and even process
1597                  * trying to open to exit/fail if not itself handling -EAGAIN.
1598                  * So it should be better to return -EINPROGRESS instead and
1599                  * leave the decision to resend at Client side in after_reply()
1600                  */
1601                 if (rc == -EWOULDBLOCK) {
1602                         rc = -EINPROGRESS;
1603                         CDEBUG(D_HA, "returning -EINPROGRESS instead of "
1604                                "-EWOULDBLOCK/-EAGAIN to allow Client to "
1605                                "resend\n");
1606                 } else {
1607                         CERROR("can't punch object: %d\n", rc);
1608                 }
1609         }
1610 out:
1611         ptlrpc_req_finished(req);
1612         if (oa)
1613                 OBD_FREE_PTR(oa);
1614         RETURN(rc);
1615 }
1616
1617 /**
1618  * Initialize precreation functionality of OSP
1619  *
1620  * Prepares all the internal structures and starts the precreate thread
1621  *
1622  * \param[in] d         OSP device
1623  *
1624  * \retval 0            on success
1625  * \retval negative     negated errno on error
1626  */
1627 int osp_init_precreate(struct osp_device *d)
1628 {
1629         struct l_wait_info       lwi = { 0 };
1630         struct task_struct              *task;
1631
1632         ENTRY;
1633
1634         OBD_ALLOC_PTR(d->opd_pre);
1635         if (d->opd_pre == NULL)
1636                 RETURN(-ENOMEM);
1637
1638         /* initially precreation isn't ready */
1639         d->opd_pre_status = -EAGAIN;
1640         fid_zero(&d->opd_pre_used_fid);
1641         d->opd_pre_used_fid.f_oid = 1;
1642         fid_zero(&d->opd_pre_last_created_fid);
1643         d->opd_pre_last_created_fid.f_oid = 1;
1644         d->opd_pre_reserved = 0;
1645         d->opd_got_disconnected = 1;
1646         d->opd_pre_create_slow = 0;
1647         d->opd_pre_create_count = OST_MIN_PRECREATE;
1648         d->opd_pre_min_create_count = OST_MIN_PRECREATE;
1649         d->opd_pre_max_create_count = OST_MAX_PRECREATE;
1650         d->opd_reserved_mb_high = 0;
1651         d->opd_reserved_mb_low = 0;
1652
1653         spin_lock_init(&d->opd_pre_lock);
1654         init_waitqueue_head(&d->opd_pre_waitq);
1655         init_waitqueue_head(&d->opd_pre_user_waitq);
1656         thread_set_flags(&d->opd_pre_thread, SVC_INIT);
1657         init_waitqueue_head(&d->opd_pre_thread.t_ctl_waitq);
1658
1659         /*
1660          * Initialize statfs-related things
1661          */
1662         d->opd_statfs_maxage = 5; /* default update interval */
1663         d->opd_statfs_fresh_till = cfs_time_shift(-1000);
1664         CDEBUG(D_OTHER, "current %llu, fresh till %llu\n",
1665                (unsigned long long)cfs_time_current(),
1666                (unsigned long long)d->opd_statfs_fresh_till);
1667         setup_timer(&d->opd_statfs_timer, osp_statfs_timer_cb,
1668                     (unsigned long)d);
1669
1670         if (d->opd_storage->dd_rdonly)
1671                 RETURN(0);
1672
1673         /*
1674          * start thread handling precreation and statfs updates
1675          */
1676         task = kthread_run(osp_precreate_thread, d,
1677                            "osp-pre-%u-%u", d->opd_index, d->opd_group);
1678         if (IS_ERR(task)) {
1679                 CERROR("can't start precreate thread %ld\n", PTR_ERR(task));
1680                 RETURN(PTR_ERR(task));
1681         }
1682
1683         l_wait_event(d->opd_pre_thread.t_ctl_waitq,
1684                      osp_precreate_running(d) || osp_precreate_stopped(d),
1685                      &lwi);
1686
1687         RETURN(0);
1688 }
1689
1690 /**
1691  * Finish precreate functionality of OSP
1692  *
1693  *
1694  * Asks all the activity (the thread, update timer) to stop, then
1695  * wait till that is done.
1696  *
1697  * \param[in] d         OSP device
1698  */
1699 void osp_precreate_fini(struct osp_device *d)
1700 {
1701         struct ptlrpc_thread *thread = &d->opd_pre_thread;
1702         ENTRY;
1703
1704         del_timer(&d->opd_statfs_timer);
1705
1706         if (d->opd_pre == NULL)
1707                 RETURN_EXIT;
1708
1709         if (!thread_is_init(thread) && !thread_is_stopped(thread)) {
1710                 thread->t_flags = SVC_STOPPING;
1711                 wake_up(&d->opd_pre_waitq);
1712                 wait_event(thread->t_ctl_waitq, thread_is_stopped(thread));
1713         }
1714
1715         OBD_FREE_PTR(d->opd_pre);
1716         d->opd_pre = NULL;
1717
1718         EXIT;
1719 }
1720