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