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