These changes are the raw update to linux-4.4.6-rt14. Kernel sources
[kvmfornfv.git] / kernel / drivers / staging / lustre / lustre / mgc / mgc_request.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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2012, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/mgc/mgc_request.c
37  *
38  * Author: Nathan Rutman <nathan@clusterfs.com>
39  */
40
41 #define DEBUG_SUBSYSTEM S_MGC
42 #define D_MGC D_CONFIG /*|D_WARNING*/
43
44 #include <linux/module.h>
45 #include "../include/obd_class.h"
46 #include "../include/lustre_dlm.h"
47 #include "../include/lprocfs_status.h"
48 #include "../include/lustre_log.h"
49 #include "../include/lustre_disk.h"
50
51 #include "mgc_internal.h"
52
53 static int mgc_name2resid(char *name, int len, struct ldlm_res_id *res_id,
54                           int type)
55 {
56         __u64 resname = 0;
57
58         if (len > sizeof(resname)) {
59                 CERROR("name too long: %s\n", name);
60                 return -EINVAL;
61         }
62         if (len <= 0) {
63                 CERROR("missing name: %s\n", name);
64                 return -EINVAL;
65         }
66         memcpy(&resname, name, len);
67
68         /* Always use the same endianness for the resid */
69         memset(res_id, 0, sizeof(*res_id));
70         res_id->name[0] = cpu_to_le64(resname);
71         /* XXX: unfortunately, sptlprc and config llog share one lock */
72         switch (type) {
73         case CONFIG_T_CONFIG:
74         case CONFIG_T_SPTLRPC:
75                 resname = 0;
76                 break;
77         case CONFIG_T_RECOVER:
78         case CONFIG_T_PARAMS:
79                 resname = type;
80                 break;
81         default:
82                 LBUG();
83         }
84         res_id->name[1] = cpu_to_le64(resname);
85         CDEBUG(D_MGC, "log %s to resid %#llx/%#llx (%.8s)\n", name,
86                res_id->name[0], res_id->name[1], (char *)&res_id->name[0]);
87         return 0;
88 }
89
90 int mgc_fsname2resid(char *fsname, struct ldlm_res_id *res_id, int type)
91 {
92         /* fsname is at most 8 chars long, maybe contain "-".
93          * e.g. "lustre", "SUN-000" */
94         return mgc_name2resid(fsname, strlen(fsname), res_id, type);
95 }
96 EXPORT_SYMBOL(mgc_fsname2resid);
97
98 static int mgc_logname2resid(char *logname, struct ldlm_res_id *res_id, int type)
99 {
100         char *name_end;
101         int len;
102
103         /* logname consists of "fsname-nodetype".
104          * e.g. "lustre-MDT0001", "SUN-000-client"
105          * there is an exception: llog "params" */
106         name_end = strrchr(logname, '-');
107         if (!name_end)
108                 len = strlen(logname);
109         else
110                 len = name_end - logname;
111         return mgc_name2resid(logname, len, res_id, type);
112 }
113
114 /********************** config llog list **********************/
115 static LIST_HEAD(config_llog_list);
116 static DEFINE_SPINLOCK(config_list_lock);
117
118 /* Take a reference to a config log */
119 static int config_log_get(struct config_llog_data *cld)
120 {
121         atomic_inc(&cld->cld_refcount);
122         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
123                atomic_read(&cld->cld_refcount));
124         return 0;
125 }
126
127 /* Drop a reference to a config log.  When no longer referenced,
128    we can free the config log data */
129 static void config_log_put(struct config_llog_data *cld)
130 {
131         CDEBUG(D_INFO, "log %s refs %d\n", cld->cld_logname,
132                atomic_read(&cld->cld_refcount));
133         LASSERT(atomic_read(&cld->cld_refcount) > 0);
134
135         /* spinlock to make sure no item with 0 refcount in the list */
136         if (atomic_dec_and_lock(&cld->cld_refcount, &config_list_lock)) {
137                 list_del(&cld->cld_list_chain);
138                 spin_unlock(&config_list_lock);
139
140                 CDEBUG(D_MGC, "dropping config log %s\n", cld->cld_logname);
141
142                 if (cld->cld_recover)
143                         config_log_put(cld->cld_recover);
144                 if (cld->cld_sptlrpc)
145                         config_log_put(cld->cld_sptlrpc);
146                 if (cld->cld_params)
147                         config_log_put(cld->cld_params);
148                 if (cld_is_sptlrpc(cld))
149                         sptlrpc_conf_log_stop(cld->cld_logname);
150
151                 class_export_put(cld->cld_mgcexp);
152                 kfree(cld);
153         }
154 }
155
156 /* Find a config log by name */
157 static
158 struct config_llog_data *config_log_find(char *logname,
159                                          struct config_llog_instance *cfg)
160 {
161         struct config_llog_data *cld;
162         struct config_llog_data *found = NULL;
163         void *instance;
164
165         LASSERT(logname != NULL);
166
167         instance = cfg ? cfg->cfg_instance : NULL;
168         spin_lock(&config_list_lock);
169         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
170                 /* check if instance equals */
171                 if (instance != cld->cld_cfg.cfg_instance)
172                         continue;
173
174                 /* instance may be NULL, should check name */
175                 if (strcmp(logname, cld->cld_logname) == 0) {
176                         found = cld;
177                         break;
178                 }
179         }
180         if (found) {
181                 atomic_inc(&found->cld_refcount);
182                 LASSERT(found->cld_stopping == 0 || cld_is_sptlrpc(found) == 0);
183         }
184         spin_unlock(&config_list_lock);
185         return found;
186 }
187
188 static
189 struct config_llog_data *do_config_log_add(struct obd_device *obd,
190                                            char *logname,
191                                            int type,
192                                            struct config_llog_instance *cfg,
193                                            struct super_block *sb)
194 {
195         struct config_llog_data *cld;
196         int                   rc;
197
198         CDEBUG(D_MGC, "do adding config log %s:%p\n", logname,
199                cfg ? cfg->cfg_instance : NULL);
200
201         cld = kzalloc(sizeof(*cld) + strlen(logname) + 1, GFP_NOFS);
202         if (!cld)
203                 return ERR_PTR(-ENOMEM);
204
205         strcpy(cld->cld_logname, logname);
206         if (cfg)
207                 cld->cld_cfg = *cfg;
208         else
209                 cld->cld_cfg.cfg_callback = class_config_llog_handler;
210         mutex_init(&cld->cld_lock);
211         cld->cld_cfg.cfg_last_idx = 0;
212         cld->cld_cfg.cfg_flags = 0;
213         cld->cld_cfg.cfg_sb = sb;
214         cld->cld_type = type;
215         atomic_set(&cld->cld_refcount, 1);
216
217         /* Keep the mgc around until we are done */
218         cld->cld_mgcexp = class_export_get(obd->obd_self_export);
219
220         if (cld_is_sptlrpc(cld)) {
221                 sptlrpc_conf_log_start(logname);
222                 cld->cld_cfg.cfg_obdname = obd->obd_name;
223         }
224
225         rc = mgc_logname2resid(logname, &cld->cld_resid, type);
226
227         spin_lock(&config_list_lock);
228         list_add(&cld->cld_list_chain, &config_llog_list);
229         spin_unlock(&config_list_lock);
230
231         if (rc) {
232                 config_log_put(cld);
233                 return ERR_PTR(rc);
234         }
235
236         if (cld_is_sptlrpc(cld)) {
237                 rc = mgc_process_log(obd, cld);
238                 if (rc && rc != -ENOENT)
239                         CERROR("failed processing sptlrpc log: %d\n", rc);
240         }
241
242         return cld;
243 }
244
245 static struct config_llog_data *config_recover_log_add(struct obd_device *obd,
246         char *fsname,
247         struct config_llog_instance *cfg,
248         struct super_block *sb)
249 {
250         struct config_llog_instance lcfg = *cfg;
251         struct config_llog_data *cld;
252         char logname[32];
253
254         /* we have to use different llog for clients and mdts for cmd
255          * where only clients are notified if one of cmd server restarts */
256         LASSERT(strlen(fsname) < sizeof(logname) / 2);
257         strcpy(logname, fsname);
258         LASSERT(lcfg.cfg_instance);
259         strcat(logname, "-cliir");
260
261         cld = do_config_log_add(obd, logname, CONFIG_T_RECOVER, &lcfg, sb);
262         return cld;
263 }
264
265 static struct config_llog_data *config_params_log_add(struct obd_device *obd,
266         struct config_llog_instance *cfg, struct super_block *sb)
267 {
268         struct config_llog_instance     lcfg = *cfg;
269         struct config_llog_data         *cld;
270
271         lcfg.cfg_instance = sb;
272
273         cld = do_config_log_add(obd, PARAMS_FILENAME, CONFIG_T_PARAMS,
274                                 &lcfg, sb);
275
276         return cld;
277 }
278
279 /** Add this log to the list of active logs watched by an MGC.
280  * Active means we're watching for updates.
281  * We have one active log per "mount" - client instance or servername.
282  * Each instance may be at a different point in the log.
283  */
284 static int config_log_add(struct obd_device *obd, char *logname,
285                           struct config_llog_instance *cfg,
286                           struct super_block *sb)
287 {
288         struct lustre_sb_info *lsi = s2lsi(sb);
289         struct config_llog_data *cld;
290         struct config_llog_data *sptlrpc_cld;
291         struct config_llog_data *params_cld;
292         char                    seclogname[32];
293         char                    *ptr;
294         int                     rc;
295
296         CDEBUG(D_MGC, "adding config log %s:%p\n", logname, cfg->cfg_instance);
297
298         /*
299          * for each regular log, the depended sptlrpc log name is
300          * <fsname>-sptlrpc. multiple regular logs may share one sptlrpc log.
301          */
302         ptr = strrchr(logname, '-');
303         if (ptr == NULL || ptr - logname > 8) {
304                 CERROR("logname %s is too long\n", logname);
305                 return -EINVAL;
306         }
307
308         memcpy(seclogname, logname, ptr - logname);
309         strcpy(seclogname + (ptr - logname), "-sptlrpc");
310
311         sptlrpc_cld = config_log_find(seclogname, NULL);
312         if (sptlrpc_cld == NULL) {
313                 sptlrpc_cld = do_config_log_add(obd, seclogname,
314                                                 CONFIG_T_SPTLRPC, NULL, NULL);
315                 if (IS_ERR(sptlrpc_cld)) {
316                         CERROR("can't create sptlrpc log: %s\n", seclogname);
317                         rc = PTR_ERR(sptlrpc_cld);
318                         goto out_err;
319                 }
320         }
321         params_cld = config_params_log_add(obd, cfg, sb);
322         if (IS_ERR(params_cld)) {
323                 rc = PTR_ERR(params_cld);
324                 CERROR("%s: can't create params log: rc = %d\n",
325                        obd->obd_name, rc);
326                 goto out_err1;
327         }
328
329         cld = do_config_log_add(obd, logname, CONFIG_T_CONFIG, cfg, sb);
330         if (IS_ERR(cld)) {
331                 CERROR("can't create log: %s\n", logname);
332                 rc = PTR_ERR(cld);
333                 goto out_err2;
334         }
335
336         cld->cld_sptlrpc = sptlrpc_cld;
337         cld->cld_params = params_cld;
338
339         LASSERT(lsi->lsi_lmd);
340         if (!(lsi->lsi_lmd->lmd_flags & LMD_FLG_NOIR)) {
341                 struct config_llog_data *recover_cld;
342                 *strrchr(seclogname, '-') = 0;
343                 recover_cld = config_recover_log_add(obd, seclogname, cfg, sb);
344                 if (IS_ERR(recover_cld)) {
345                         rc = PTR_ERR(recover_cld);
346                         goto out_err3;
347                 }
348                 cld->cld_recover = recover_cld;
349         }
350
351         return 0;
352
353 out_err3:
354         config_log_put(cld);
355
356 out_err2:
357         config_log_put(params_cld);
358
359 out_err1:
360         config_log_put(sptlrpc_cld);
361
362 out_err:
363         return rc;
364 }
365
366 DEFINE_MUTEX(llog_process_lock);
367
368 /** Stop watching for updates on this log.
369  */
370 static int config_log_end(char *logname, struct config_llog_instance *cfg)
371 {
372         struct config_llog_data *cld;
373         struct config_llog_data *cld_sptlrpc = NULL;
374         struct config_llog_data *cld_params = NULL;
375         struct config_llog_data *cld_recover = NULL;
376         int rc = 0;
377
378         cld = config_log_find(logname, cfg);
379         if (cld == NULL)
380                 return -ENOENT;
381
382         mutex_lock(&cld->cld_lock);
383         /*
384          * if cld_stopping is set, it means we didn't start the log thus
385          * not owning the start ref. this can happen after previous umount:
386          * the cld still hanging there waiting for lock cancel, and we
387          * remount again but failed in the middle and call log_end without
388          * calling start_log.
389          */
390         if (unlikely(cld->cld_stopping)) {
391                 mutex_unlock(&cld->cld_lock);
392                 /* drop the ref from the find */
393                 config_log_put(cld);
394                 return rc;
395         }
396
397         cld->cld_stopping = 1;
398
399         cld_recover = cld->cld_recover;
400         cld->cld_recover = NULL;
401         mutex_unlock(&cld->cld_lock);
402
403         if (cld_recover) {
404                 mutex_lock(&cld_recover->cld_lock);
405                 cld_recover->cld_stopping = 1;
406                 mutex_unlock(&cld_recover->cld_lock);
407                 config_log_put(cld_recover);
408         }
409
410         spin_lock(&config_list_lock);
411         cld_sptlrpc = cld->cld_sptlrpc;
412         cld->cld_sptlrpc = NULL;
413         cld_params = cld->cld_params;
414         cld->cld_params = NULL;
415         spin_unlock(&config_list_lock);
416
417         if (cld_sptlrpc)
418                 config_log_put(cld_sptlrpc);
419
420         if (cld_params) {
421                 mutex_lock(&cld_params->cld_lock);
422                 cld_params->cld_stopping = 1;
423                 mutex_unlock(&cld_params->cld_lock);
424                 config_log_put(cld_params);
425         }
426
427         /* drop the ref from the find */
428         config_log_put(cld);
429         /* drop the start ref */
430         config_log_put(cld);
431
432         CDEBUG(D_MGC, "end config log %s (%d)\n", logname ? logname : "client",
433                rc);
434         return rc;
435 }
436
437 int lprocfs_mgc_rd_ir_state(struct seq_file *m, void *data)
438 {
439         struct obd_device       *obd = data;
440         struct obd_import       *imp;
441         struct obd_connect_data *ocd;
442         struct config_llog_data *cld;
443         int rc;
444
445         rc = lprocfs_climp_check(obd);
446         if (rc)
447                 return rc;
448
449         imp = obd->u.cli.cl_import;
450         ocd = &imp->imp_connect_data;
451
452         seq_printf(m, "imperative_recovery: %s\n",
453                       OCD_HAS_FLAG(ocd, IMP_RECOV) ? "ENABLED" : "DISABLED");
454         seq_printf(m, "client_state:\n");
455
456         spin_lock(&config_list_lock);
457         list_for_each_entry(cld, &config_llog_list, cld_list_chain) {
458                 if (cld->cld_recover == NULL)
459                         continue;
460                 seq_printf(m,  "    - { client: %s, nidtbl_version: %u }\n",
461                                cld->cld_logname,
462                                cld->cld_recover->cld_cfg.cfg_last_idx);
463         }
464         spin_unlock(&config_list_lock);
465
466         LPROCFS_CLIMP_EXIT(obd);
467         return 0;
468 }
469
470 /* reenqueue any lost locks */
471 #define RQ_RUNNING 0x1
472 #define RQ_NOW     0x2
473 #define RQ_LATER   0x4
474 #define RQ_STOP    0x8
475 #define RQ_PRECLEANUP  0x10
476 static int rq_state;
477 static wait_queue_head_t            rq_waitq;
478 static DECLARE_COMPLETION(rq_exit);
479 static DECLARE_COMPLETION(rq_start);
480
481 static void do_requeue(struct config_llog_data *cld)
482 {
483         LASSERT(atomic_read(&cld->cld_refcount) > 0);
484
485         /* Do not run mgc_process_log on a disconnected export or an
486            export which is being disconnected. Take the client
487            semaphore to make the check non-racy. */
488         down_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
489         if (cld->cld_mgcexp->exp_obd->u.cli.cl_conn_count != 0) {
490                 CDEBUG(D_MGC, "updating log %s\n", cld->cld_logname);
491                 mgc_process_log(cld->cld_mgcexp->exp_obd, cld);
492         } else {
493                 CDEBUG(D_MGC, "disconnecting, won't update log %s\n",
494                        cld->cld_logname);
495         }
496         up_read(&cld->cld_mgcexp->exp_obd->u.cli.cl_sem);
497 }
498
499 /* this timeout represents how many seconds MGC should wait before
500  * requeue config and recover lock to the MGS. We need to randomize this
501  * in order to not flood the MGS.
502  */
503 #define MGC_TIMEOUT_MIN_SECONDS   5
504 #define MGC_TIMEOUT_RAND_CENTISEC 0x1ff /* ~500 */
505
506 static int mgc_requeue_thread(void *data)
507 {
508         bool first = true;
509
510         CDEBUG(D_MGC, "Starting requeue thread\n");
511
512         /* Keep trying failed locks periodically */
513         spin_lock(&config_list_lock);
514         rq_state |= RQ_RUNNING;
515         while (1) {
516                 struct l_wait_info lwi;
517                 struct config_llog_data *cld, *cld_prev;
518                 int rand = cfs_rand() & MGC_TIMEOUT_RAND_CENTISEC;
519                 int stopped = !!(rq_state & RQ_STOP);
520                 int to;
521
522                 /* Any new or requeued lostlocks will change the state */
523                 rq_state &= ~(RQ_NOW | RQ_LATER);
524                 spin_unlock(&config_list_lock);
525
526                 if (first) {
527                         first = false;
528                         complete(&rq_start);
529                 }
530
531                 /* Always wait a few seconds to allow the server who
532                    caused the lock revocation to finish its setup, plus some
533                    random so everyone doesn't try to reconnect at once. */
534                 to = MGC_TIMEOUT_MIN_SECONDS * HZ;
535                 to += rand * HZ / 100; /* rand is centi-seconds */
536                 lwi = LWI_TIMEOUT(to, NULL, NULL);
537                 l_wait_event(rq_waitq, rq_state & (RQ_STOP | RQ_PRECLEANUP),
538                              &lwi);
539
540                 /*
541                  * iterate & processing through the list. for each cld, process
542                  * its depending sptlrpc cld firstly (if any) and then itself.
543                  *
544                  * it's guaranteed any item in the list must have
545                  * reference > 0; and if cld_lostlock is set, at
546                  * least one reference is taken by the previous enqueue.
547                  */
548                 cld_prev = NULL;
549
550                 spin_lock(&config_list_lock);
551                 rq_state &= ~RQ_PRECLEANUP;
552                 list_for_each_entry(cld, &config_llog_list,
553                                         cld_list_chain) {
554                         if (!cld->cld_lostlock)
555                                 continue;
556
557                         spin_unlock(&config_list_lock);
558
559                         LASSERT(atomic_read(&cld->cld_refcount) > 0);
560
561                         /* Whether we enqueued again or not in mgc_process_log,
562                          * we're done with the ref from the old enqueue */
563                         if (cld_prev)
564                                 config_log_put(cld_prev);
565                         cld_prev = cld;
566
567                         cld->cld_lostlock = 0;
568                         if (likely(!stopped))
569                                 do_requeue(cld);
570
571                         spin_lock(&config_list_lock);
572                 }
573                 spin_unlock(&config_list_lock);
574                 if (cld_prev)
575                         config_log_put(cld_prev);
576
577                 /* break after scanning the list so that we can drop
578                  * refcount to losing lock clds */
579                 if (unlikely(stopped)) {
580                         spin_lock(&config_list_lock);
581                         break;
582                 }
583
584                 /* Wait a bit to see if anyone else needs a requeue */
585                 lwi = (struct l_wait_info) { 0 };
586                 l_wait_event(rq_waitq, rq_state & (RQ_NOW | RQ_STOP),
587                              &lwi);
588                 spin_lock(&config_list_lock);
589         }
590         /* spinlock and while guarantee RQ_NOW and RQ_LATER are not set */
591         rq_state &= ~RQ_RUNNING;
592         spin_unlock(&config_list_lock);
593
594         complete(&rq_exit);
595
596         CDEBUG(D_MGC, "Ending requeue thread\n");
597         return 0;
598 }
599
600 /* Add a cld to the list to requeue.  Start the requeue thread if needed.
601    We are responsible for dropping the config log reference from here on out. */
602 static void mgc_requeue_add(struct config_llog_data *cld)
603 {
604         CDEBUG(D_INFO, "log %s: requeue (r=%d sp=%d st=%x)\n",
605                cld->cld_logname, atomic_read(&cld->cld_refcount),
606                cld->cld_stopping, rq_state);
607         LASSERT(atomic_read(&cld->cld_refcount) > 0);
608
609         mutex_lock(&cld->cld_lock);
610         if (cld->cld_stopping || cld->cld_lostlock) {
611                 mutex_unlock(&cld->cld_lock);
612                 return;
613         }
614         /* this refcount will be released in mgc_requeue_thread. */
615         config_log_get(cld);
616         cld->cld_lostlock = 1;
617         mutex_unlock(&cld->cld_lock);
618
619         /* Hold lock for rq_state */
620         spin_lock(&config_list_lock);
621         if (rq_state & RQ_STOP) {
622                 spin_unlock(&config_list_lock);
623                 cld->cld_lostlock = 0;
624                 config_log_put(cld);
625         } else {
626                 rq_state |= RQ_NOW;
627                 spin_unlock(&config_list_lock);
628                 wake_up(&rq_waitq);
629         }
630 }
631
632 static int mgc_llog_init(const struct lu_env *env, struct obd_device *obd)
633 {
634         struct llog_ctxt        *ctxt;
635         int                      rc;
636
637         /* setup only remote ctxt, the local disk context is switched per each
638          * filesystem during mgc_fs_setup() */
639         rc = llog_setup(env, obd, &obd->obd_olg, LLOG_CONFIG_REPL_CTXT, obd,
640                         &llog_client_ops);
641         if (rc)
642                 return rc;
643
644         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
645         LASSERT(ctxt);
646
647         llog_initiator_connect(ctxt);
648         llog_ctxt_put(ctxt);
649
650         return 0;
651 }
652
653 static int mgc_llog_fini(const struct lu_env *env, struct obd_device *obd)
654 {
655         struct llog_ctxt *ctxt;
656
657         ctxt = llog_get_context(obd, LLOG_CONFIG_REPL_CTXT);
658         if (ctxt)
659                 llog_cleanup(env, ctxt);
660
661         return 0;
662 }
663
664 static atomic_t mgc_count = ATOMIC_INIT(0);
665 static int mgc_precleanup(struct obd_device *obd, enum obd_cleanup_stage stage)
666 {
667         int rc = 0;
668         int temp;
669
670         switch (stage) {
671         case OBD_CLEANUP_EARLY:
672                 break;
673         case OBD_CLEANUP_EXPORTS:
674                 if (atomic_dec_and_test(&mgc_count)) {
675                         LASSERT(rq_state & RQ_RUNNING);
676                         /* stop requeue thread */
677                         temp = RQ_STOP;
678                 } else {
679                         /* wakeup requeue thread to clean our cld */
680                         temp = RQ_NOW | RQ_PRECLEANUP;
681                 }
682                 spin_lock(&config_list_lock);
683                 rq_state |= temp;
684                 spin_unlock(&config_list_lock);
685                 wake_up(&rq_waitq);
686                 if (temp & RQ_STOP)
687                         wait_for_completion(&rq_exit);
688                 obd_cleanup_client_import(obd);
689                 rc = mgc_llog_fini(NULL, obd);
690                 if (rc != 0)
691                         CERROR("failed to cleanup llogging subsystems\n");
692                 break;
693         }
694         return rc;
695 }
696
697 static int mgc_cleanup(struct obd_device *obd)
698 {
699         /* COMPAT_146 - old config logs may have added profiles we don't
700            know about */
701         if (obd->obd_type->typ_refcnt <= 1)
702                 /* Only for the last mgc */
703                 class_del_profiles();
704
705         lprocfs_obd_cleanup(obd);
706         ptlrpcd_decref();
707
708         return client_obd_cleanup(obd);
709 }
710
711 static int mgc_setup(struct obd_device *obd, struct lustre_cfg *lcfg)
712 {
713         struct lprocfs_static_vars lvars = { NULL };
714         int rc;
715
716         ptlrpcd_addref();
717
718         rc = client_obd_setup(obd, lcfg);
719         if (rc)
720                 goto err_decref;
721
722         rc = mgc_llog_init(NULL, obd);
723         if (rc) {
724                 CERROR("failed to setup llogging subsystems\n");
725                 goto err_cleanup;
726         }
727
728         lprocfs_mgc_init_vars(&lvars);
729         lprocfs_obd_setup(obd, lvars.obd_vars, lvars.sysfs_vars);
730         sptlrpc_lprocfs_cliobd_attach(obd);
731
732         if (atomic_inc_return(&mgc_count) == 1) {
733                 rq_state = 0;
734                 init_waitqueue_head(&rq_waitq);
735
736                 /* start requeue thread */
737                 rc = PTR_ERR(kthread_run(mgc_requeue_thread, NULL,
738                                              "ll_cfg_requeue"));
739                 if (IS_ERR_VALUE(rc)) {
740                         CERROR("%s: Cannot start requeue thread (%d),no more log updates!\n",
741                                obd->obd_name, rc);
742                         goto err_cleanup;
743                 }
744                 /* rc is the task_struct pointer of mgc_requeue_thread. */
745                 rc = 0;
746                 wait_for_completion(&rq_start);
747         }
748
749         return rc;
750
751 err_cleanup:
752         client_obd_cleanup(obd);
753 err_decref:
754         ptlrpcd_decref();
755         return rc;
756 }
757
758 /* based on ll_mdc_blocking_ast */
759 static int mgc_blocking_ast(struct ldlm_lock *lock, struct ldlm_lock_desc *desc,
760                             void *data, int flag)
761 {
762         struct lustre_handle lockh;
763         struct config_llog_data *cld = data;
764         int rc = 0;
765
766         switch (flag) {
767         case LDLM_CB_BLOCKING:
768                 /* mgs wants the lock, give it up... */
769                 LDLM_DEBUG(lock, "MGC blocking CB");
770                 ldlm_lock2handle(lock, &lockh);
771                 rc = ldlm_cli_cancel(&lockh, LCF_ASYNC);
772                 break;
773         case LDLM_CB_CANCELING:
774                 /* We've given up the lock, prepare ourselves to update. */
775                 LDLM_DEBUG(lock, "MGC cancel CB");
776
777                 CDEBUG(D_MGC, "Lock res "DLDLMRES" (%.8s)\n",
778                        PLDLMRES(lock->l_resource),
779                        (char *)&lock->l_resource->lr_name.name[0]);
780
781                 if (!cld) {
782                         CDEBUG(D_INFO, "missing data, won't requeue\n");
783                         break;
784                 }
785
786                 /* held at mgc_process_log(). */
787                 LASSERT(atomic_read(&cld->cld_refcount) > 0);
788                 /* Are we done with this log? */
789                 if (cld->cld_stopping) {
790                         CDEBUG(D_MGC, "log %s: stopping, won't requeue\n",
791                                cld->cld_logname);
792                         config_log_put(cld);
793                         break;
794                 }
795                 /* Make sure not to re-enqueue when the mgc is stopping
796                    (we get called from client_disconnect_export) */
797                 if (!lock->l_conn_export ||
798                     !lock->l_conn_export->exp_obd->u.cli.cl_conn_count) {
799                         CDEBUG(D_MGC, "log %.8s: disconnecting, won't requeue\n",
800                                cld->cld_logname);
801                         config_log_put(cld);
802                         break;
803                 }
804
805                 /* Re-enqueue now */
806                 mgc_requeue_add(cld);
807                 config_log_put(cld);
808                 break;
809         default:
810                 LBUG();
811         }
812
813         return rc;
814 }
815
816 /* Not sure where this should go... */
817 /* This is the timeout value for MGS_CONNECT request plus a ping interval, such
818  * that we can have a chance to try the secondary MGS if any. */
819 #define  MGC_ENQUEUE_LIMIT (INITIAL_CONNECT_TIMEOUT + (AT_OFF ? 0 : at_min) \
820                                 + PING_INTERVAL)
821 #define  MGC_TARGET_REG_LIMIT 10
822 #define  MGC_SEND_PARAM_LIMIT 10
823
824 /* Send parameter to MGS*/
825 static int mgc_set_mgs_param(struct obd_export *exp,
826                              struct mgs_send_param *msp)
827 {
828         struct ptlrpc_request *req;
829         struct mgs_send_param *req_msp, *rep_msp;
830         int rc;
831
832         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
833                                         &RQF_MGS_SET_INFO, LUSTRE_MGS_VERSION,
834                                         MGS_SET_INFO);
835         if (!req)
836                 return -ENOMEM;
837
838         req_msp = req_capsule_client_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
839         if (!req_msp) {
840                 ptlrpc_req_finished(req);
841                 return -ENOMEM;
842         }
843
844         memcpy(req_msp, msp, sizeof(*req_msp));
845         ptlrpc_request_set_replen(req);
846
847         /* Limit how long we will wait for the enqueue to complete */
848         req->rq_delay_limit = MGC_SEND_PARAM_LIMIT;
849         rc = ptlrpc_queue_wait(req);
850         if (!rc) {
851                 rep_msp = req_capsule_server_get(&req->rq_pill, &RMF_MGS_SEND_PARAM);
852                 memcpy(msp, rep_msp, sizeof(*rep_msp));
853         }
854
855         ptlrpc_req_finished(req);
856
857         return rc;
858 }
859
860 /* Take a config lock so we can get cancel notifications */
861 static int mgc_enqueue(struct obd_export *exp, struct lov_stripe_md *lsm,
862                        __u32 type, ldlm_policy_data_t *policy, __u32 mode,
863                        __u64 *flags, void *bl_cb, void *cp_cb, void *gl_cb,
864                        void *data, __u32 lvb_len, void *lvb_swabber,
865                        struct lustre_handle *lockh)
866 {
867         struct config_llog_data *cld = data;
868         struct ldlm_enqueue_info einfo = {
869                 .ei_type        = type,
870                 .ei_mode        = mode,
871                 .ei_cb_bl       = mgc_blocking_ast,
872                 .ei_cb_cp       = ldlm_completion_ast,
873         };
874         struct ptlrpc_request *req;
875         int short_limit = cld_is_sptlrpc(cld);
876         int rc;
877
878         CDEBUG(D_MGC, "Enqueue for %s (res %#llx)\n", cld->cld_logname,
879                cld->cld_resid.name[0]);
880
881         /* We need a callback for every lockholder, so don't try to
882            ldlm_lock_match (see rev 1.1.2.11.2.47) */
883         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
884                                         &RQF_LDLM_ENQUEUE, LUSTRE_DLM_VERSION,
885                                         LDLM_ENQUEUE);
886         if (req == NULL)
887                 return -ENOMEM;
888
889         req_capsule_set_size(&req->rq_pill, &RMF_DLM_LVB, RCL_SERVER, 0);
890         ptlrpc_request_set_replen(req);
891
892         /* Limit how long we will wait for the enqueue to complete */
893         req->rq_delay_limit = short_limit ? 5 : MGC_ENQUEUE_LIMIT;
894         rc = ldlm_cli_enqueue(exp, &req, &einfo, &cld->cld_resid, NULL, flags,
895                               NULL, 0, LVB_T_NONE, lockh, 0);
896         /* A failed enqueue should still call the mgc_blocking_ast,
897            where it will be requeued if needed ("grant failed"). */
898         ptlrpc_req_finished(req);
899         return rc;
900 }
901
902 static void mgc_notify_active(struct obd_device *unused)
903 {
904         /* wakeup mgc_requeue_thread to requeue mgc lock */
905         spin_lock(&config_list_lock);
906         rq_state |= RQ_NOW;
907         spin_unlock(&config_list_lock);
908         wake_up(&rq_waitq);
909
910         /* TODO: Help the MGS rebuild nidtbl. -jay */
911 }
912
913 /* Send target_reg message to MGS */
914 static int mgc_target_register(struct obd_export *exp,
915                                struct mgs_target_info *mti)
916 {
917         struct ptlrpc_request  *req;
918         struct mgs_target_info *req_mti, *rep_mti;
919         int                  rc;
920
921         req = ptlrpc_request_alloc_pack(class_exp2cliimp(exp),
922                                         &RQF_MGS_TARGET_REG, LUSTRE_MGS_VERSION,
923                                         MGS_TARGET_REG);
924         if (req == NULL)
925                 return -ENOMEM;
926
927         req_mti = req_capsule_client_get(&req->rq_pill, &RMF_MGS_TARGET_INFO);
928         if (!req_mti) {
929                 ptlrpc_req_finished(req);
930                 return -ENOMEM;
931         }
932
933         memcpy(req_mti, mti, sizeof(*req_mti));
934         ptlrpc_request_set_replen(req);
935         CDEBUG(D_MGC, "register %s\n", mti->mti_svname);
936         /* Limit how long we will wait for the enqueue to complete */
937         req->rq_delay_limit = MGC_TARGET_REG_LIMIT;
938
939         rc = ptlrpc_queue_wait(req);
940         if (!rc) {
941                 rep_mti = req_capsule_server_get(&req->rq_pill,
942                                                  &RMF_MGS_TARGET_INFO);
943                 memcpy(mti, rep_mti, sizeof(*rep_mti));
944                 CDEBUG(D_MGC, "register %s got index = %d\n",
945                        mti->mti_svname, mti->mti_stripe_index);
946         }
947         ptlrpc_req_finished(req);
948
949         return rc;
950 }
951
952 static int mgc_set_info_async(const struct lu_env *env, struct obd_export *exp,
953                        u32 keylen, void *key, u32 vallen,
954                        void *val, struct ptlrpc_request_set *set)
955 {
956         int rc = -EINVAL;
957
958         /* Turn off initial_recov after we try all backup servers once */
959         if (KEY_IS(KEY_INIT_RECOV_BACKUP)) {
960                 struct obd_import *imp = class_exp2cliimp(exp);
961                 int value;
962
963                 if (vallen != sizeof(int))
964                         return -EINVAL;
965                 value = *(int *)val;
966                 CDEBUG(D_MGC, "InitRecov %s %d/d%d:i%d:r%d:or%d:%s\n",
967                        imp->imp_obd->obd_name, value,
968                        imp->imp_deactive, imp->imp_invalid,
969                        imp->imp_replayable, imp->imp_obd->obd_replayable,
970                        ptlrpc_import_state_name(imp->imp_state));
971                 /* Resurrect if we previously died */
972                 if ((imp->imp_state != LUSTRE_IMP_FULL &&
973                      imp->imp_state != LUSTRE_IMP_NEW) || value > 1)
974                         ptlrpc_reconnect_import(imp);
975                 return 0;
976         }
977         if (KEY_IS(KEY_SET_INFO)) {
978                 struct mgs_send_param *msp;
979
980                 msp = val;
981                 rc =  mgc_set_mgs_param(exp, msp);
982                 return rc;
983         }
984         if (KEY_IS(KEY_MGSSEC)) {
985                 struct client_obd     *cli = &exp->exp_obd->u.cli;
986                 struct sptlrpc_flavor  flvr;
987
988                 /*
989                  * empty string means using current flavor, if which haven't
990                  * been set yet, set it as null.
991                  *
992                  * if flavor has been set previously, check the asking flavor
993                  * must match the existing one.
994                  */
995                 if (vallen == 0) {
996                         if (cli->cl_flvr_mgc.sf_rpc != SPTLRPC_FLVR_INVALID)
997                                 return 0;
998                         val = "null";
999                         vallen = 4;
1000                 }
1001
1002                 rc = sptlrpc_parse_flavor(val, &flvr);
1003                 if (rc) {
1004                         CERROR("invalid sptlrpc flavor %s to MGS\n",
1005                                (char *) val);
1006                         return rc;
1007                 }
1008
1009                 /*
1010                  * caller already hold a mutex
1011                  */
1012                 if (cli->cl_flvr_mgc.sf_rpc == SPTLRPC_FLVR_INVALID) {
1013                         cli->cl_flvr_mgc = flvr;
1014                 } else if (memcmp(&cli->cl_flvr_mgc, &flvr,
1015                                   sizeof(flvr)) != 0) {
1016                         char    str[20];
1017
1018                         sptlrpc_flavor2name(&cli->cl_flvr_mgc,
1019                                             str, sizeof(str));
1020                         LCONSOLE_ERROR("asking sptlrpc flavor %s to MGS but currently %s is in use\n",
1021                                        (char *) val, str);
1022                         rc = -EPERM;
1023                 }
1024                 return rc;
1025         }
1026
1027         return rc;
1028 }
1029
1030 static int mgc_get_info(const struct lu_env *env, struct obd_export *exp,
1031                         __u32 keylen, void *key, __u32 *vallen, void *val,
1032                         struct lov_stripe_md *unused)
1033 {
1034         int rc = -EINVAL;
1035
1036         if (KEY_IS(KEY_CONN_DATA)) {
1037                 struct obd_import *imp = class_exp2cliimp(exp);
1038                 struct obd_connect_data *data = val;
1039
1040                 if (*vallen == sizeof(*data)) {
1041                         *data = imp->imp_connect_data;
1042                         rc = 0;
1043                 }
1044         }
1045
1046         return rc;
1047 }
1048
1049 static int mgc_import_event(struct obd_device *obd,
1050                             struct obd_import *imp,
1051                             enum obd_import_event event)
1052 {
1053         LASSERT(imp->imp_obd == obd);
1054         CDEBUG(D_MGC, "import event %#x\n", event);
1055
1056         switch (event) {
1057         case IMP_EVENT_DISCON:
1058                 /* MGC imports should not wait for recovery */
1059                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1060                         ptlrpc_pinger_ir_down();
1061                 break;
1062         case IMP_EVENT_INACTIVE:
1063                 break;
1064         case IMP_EVENT_INVALIDATE: {
1065                 struct ldlm_namespace *ns = obd->obd_namespace;
1066
1067                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
1068                 break;
1069         }
1070         case IMP_EVENT_ACTIVE:
1071                 CDEBUG(D_INFO, "%s: Reactivating import\n", obd->obd_name);
1072                 /* Clearing obd_no_recov allows us to continue pinging */
1073                 obd->obd_no_recov = 0;
1074                 mgc_notify_active(obd);
1075                 if (OCD_HAS_FLAG(&imp->imp_connect_data, IMP_RECOV))
1076                         ptlrpc_pinger_ir_up();
1077                 break;
1078         case IMP_EVENT_OCD:
1079                 break;
1080         case IMP_EVENT_DEACTIVATE:
1081         case IMP_EVENT_ACTIVATE:
1082                 break;
1083         default:
1084                 CERROR("Unknown import event %#x\n", event);
1085                 LBUG();
1086         }
1087         return 0;
1088 }
1089
1090 enum {
1091         CONFIG_READ_NRPAGES_INIT = 1 << (20 - PAGE_CACHE_SHIFT),
1092         CONFIG_READ_NRPAGES      = 4
1093 };
1094
1095 static int mgc_apply_recover_logs(struct obd_device *mgc,
1096                                   struct config_llog_data *cld,
1097                                   __u64 max_version,
1098                                   void *data, int datalen, bool mne_swab)
1099 {
1100         struct config_llog_instance *cfg = &cld->cld_cfg;
1101         struct mgs_nidtbl_entry *entry;
1102         struct lustre_cfg       *lcfg;
1103         struct lustre_cfg_bufs   bufs;
1104         u64   prev_version = 0;
1105         char *inst;
1106         char *buf;
1107         int   bufsz;
1108         int   pos;
1109         int   rc  = 0;
1110         int   off = 0;
1111
1112         LASSERT(cfg->cfg_instance != NULL);
1113         LASSERT(cfg->cfg_sb == cfg->cfg_instance);
1114
1115         inst = kzalloc(PAGE_CACHE_SIZE, GFP_KERNEL);
1116         if (!inst)
1117                 return -ENOMEM;
1118
1119         pos = snprintf(inst, PAGE_CACHE_SIZE, "%p", cfg->cfg_instance);
1120         if (pos >= PAGE_CACHE_SIZE) {
1121                 kfree(inst);
1122                 return -E2BIG;
1123         }
1124
1125         ++pos;
1126         buf   = inst + pos;
1127         bufsz = PAGE_CACHE_SIZE - pos;
1128
1129         while (datalen > 0) {
1130                 int   entry_len = sizeof(*entry);
1131                 int   is_ost;
1132                 struct obd_device *obd;
1133                 char *obdname;
1134                 char *cname;
1135                 char *params;
1136                 char *uuid;
1137
1138                 rc = -EINVAL;
1139                 if (datalen < sizeof(*entry))
1140                         break;
1141
1142                 entry = (typeof(entry))(data + off);
1143
1144                 /* sanity check */
1145                 if (entry->mne_nid_type != 0) /* only support type 0 for ipv4 */
1146                         break;
1147                 if (entry->mne_nid_count == 0) /* at least one nid entry */
1148                         break;
1149                 if (entry->mne_nid_size != sizeof(lnet_nid_t))
1150                         break;
1151
1152                 entry_len += entry->mne_nid_count * entry->mne_nid_size;
1153                 if (datalen < entry_len) /* must have entry_len at least */
1154                         break;
1155
1156                 /* Keep this swab for normal mixed endian handling. LU-1644 */
1157                 if (mne_swab)
1158                         lustre_swab_mgs_nidtbl_entry(entry);
1159                 if (entry->mne_length > PAGE_CACHE_SIZE) {
1160                         CERROR("MNE too large (%u)\n", entry->mne_length);
1161                         break;
1162                 }
1163
1164                 if (entry->mne_length < entry_len)
1165                         break;
1166
1167                 off     += entry->mne_length;
1168                 datalen -= entry->mne_length;
1169                 if (datalen < 0)
1170                         break;
1171
1172                 if (entry->mne_version > max_version) {
1173                         CERROR("entry index(%lld) is over max_index(%lld)\n",
1174                                entry->mne_version, max_version);
1175                         break;
1176                 }
1177
1178                 if (prev_version >= entry->mne_version) {
1179                         CERROR("index unsorted, prev %lld, now %lld\n",
1180                                prev_version, entry->mne_version);
1181                         break;
1182                 }
1183                 prev_version = entry->mne_version;
1184
1185                 /*
1186                  * Write a string with format "nid::instance" to
1187                  * lustre/<osc|mdc>/<target>-<osc|mdc>-<instance>/import.
1188                  */
1189
1190                 is_ost = entry->mne_type == LDD_F_SV_TYPE_OST;
1191                 memset(buf, 0, bufsz);
1192                 obdname = buf;
1193                 pos = 0;
1194
1195                 /* lustre-OST0001-osc-<instance #> */
1196                 strcpy(obdname, cld->cld_logname);
1197                 cname = strrchr(obdname, '-');
1198                 if (cname == NULL) {
1199                         CERROR("mgc %s: invalid logname %s\n",
1200                                mgc->obd_name, obdname);
1201                         break;
1202                 }
1203
1204                 pos = cname - obdname;
1205                 obdname[pos] = 0;
1206                 pos += sprintf(obdname + pos, "-%s%04x",
1207                                   is_ost ? "OST" : "MDT", entry->mne_index);
1208
1209                 cname = is_ost ? "osc" : "mdc";
1210                 pos += sprintf(obdname + pos, "-%s-%s", cname, inst);
1211                 lustre_cfg_bufs_reset(&bufs, obdname);
1212
1213                 /* find the obd by obdname */
1214                 obd = class_name2obd(obdname);
1215                 if (obd == NULL) {
1216                         CDEBUG(D_INFO, "mgc %s: cannot find obdname %s\n",
1217                                mgc->obd_name, obdname);
1218                         rc = 0;
1219                         /* this is a safe race, when the ost is starting up...*/
1220                         continue;
1221                 }
1222
1223                 /* osc.import = "connection=<Conn UUID>::<target instance>" */
1224                 ++pos;
1225                 params = buf + pos;
1226                 pos += sprintf(params, "%s.import=%s", cname, "connection=");
1227                 uuid = buf + pos;
1228
1229                 down_read(&obd->u.cli.cl_sem);
1230                 if (obd->u.cli.cl_import == NULL) {
1231                         /* client does not connect to the OST yet */
1232                         up_read(&obd->u.cli.cl_sem);
1233                         rc = 0;
1234                         continue;
1235                 }
1236
1237                 /* TODO: iterate all nids to find one */
1238                 /* find uuid by nid */
1239                 rc = client_import_find_conn(obd->u.cli.cl_import,
1240                                              entry->u.nids[0],
1241                                              (struct obd_uuid *)uuid);
1242                 up_read(&obd->u.cli.cl_sem);
1243                 if (rc < 0) {
1244                         CERROR("mgc: cannot find uuid by nid %s\n",
1245                                libcfs_nid2str(entry->u.nids[0]));
1246                         break;
1247                 }
1248
1249                 CDEBUG(D_INFO, "Find uuid %s by nid %s\n",
1250                        uuid, libcfs_nid2str(entry->u.nids[0]));
1251
1252                 pos += strlen(uuid);
1253                 pos += sprintf(buf + pos, "::%u", entry->mne_instance);
1254                 LASSERT(pos < bufsz);
1255
1256                 lustre_cfg_bufs_set_string(&bufs, 1, params);
1257
1258                 rc = -ENOMEM;
1259                 lcfg = lustre_cfg_new(LCFG_PARAM, &bufs);
1260                 if (lcfg == NULL) {
1261                         CERROR("mgc: cannot allocate memory\n");
1262                         break;
1263                 }
1264
1265                 CDEBUG(D_INFO, "ir apply logs %lld/%lld for %s -> %s\n",
1266                        prev_version, max_version, obdname, params);
1267
1268                 rc = class_process_config(lcfg);
1269                 lustre_cfg_free(lcfg);
1270                 if (rc)
1271                         CDEBUG(D_INFO, "process config for %s error %d\n",
1272                                obdname, rc);
1273
1274                 /* continue, even one with error */
1275         }
1276
1277         kfree(inst);
1278         return rc;
1279 }
1280
1281 /**
1282  * This function is called if this client was notified for target restarting
1283  * by the MGS. A CONFIG_READ RPC is going to send to fetch recovery logs.
1284  */
1285 static int mgc_process_recover_log(struct obd_device *obd,
1286                                    struct config_llog_data *cld)
1287 {
1288         struct ptlrpc_request *req = NULL;
1289         struct config_llog_instance *cfg = &cld->cld_cfg;
1290         struct mgs_config_body *body;
1291         struct mgs_config_res  *res;
1292         struct ptlrpc_bulk_desc *desc;
1293         struct page **pages;
1294         int nrpages;
1295         bool eof = true;
1296         bool mne_swab = false;
1297         int i;
1298         int ealen;
1299         int rc;
1300
1301         /* allocate buffer for bulk transfer.
1302          * if this is the first time for this mgs to read logs,
1303          * CONFIG_READ_NRPAGES_INIT will be used since it will read all logs
1304          * once; otherwise, it only reads increment of logs, this should be
1305          * small and CONFIG_READ_NRPAGES will be used.
1306          */
1307         nrpages = CONFIG_READ_NRPAGES;
1308         if (cfg->cfg_last_idx == 0) /* the first time */
1309                 nrpages = CONFIG_READ_NRPAGES_INIT;
1310
1311         pages = kcalloc(nrpages, sizeof(*pages), GFP_KERNEL);
1312         if (pages == NULL) {
1313                 rc = -ENOMEM;
1314                 goto out;
1315         }
1316
1317         for (i = 0; i < nrpages; i++) {
1318                 pages[i] = alloc_page(GFP_KERNEL);
1319                 if (pages[i] == NULL) {
1320                         rc = -ENOMEM;
1321                         goto out;
1322                 }
1323         }
1324
1325 again:
1326         LASSERT(cld_is_recover(cld));
1327         LASSERT(mutex_is_locked(&cld->cld_lock));
1328         req = ptlrpc_request_alloc(class_exp2cliimp(cld->cld_mgcexp),
1329                                    &RQF_MGS_CONFIG_READ);
1330         if (req == NULL) {
1331                 rc = -ENOMEM;
1332                 goto out;
1333         }
1334
1335         rc = ptlrpc_request_pack(req, LUSTRE_MGS_VERSION, MGS_CONFIG_READ);
1336         if (rc)
1337                 goto out;
1338
1339         /* pack request */
1340         body = req_capsule_client_get(&req->rq_pill, &RMF_MGS_CONFIG_BODY);
1341         LASSERT(body != NULL);
1342         LASSERT(sizeof(body->mcb_name) > strlen(cld->cld_logname));
1343         if (strlcpy(body->mcb_name, cld->cld_logname, sizeof(body->mcb_name))
1344             >= sizeof(body->mcb_name)) {
1345                 rc = -E2BIG;
1346                 goto out;
1347         }
1348         body->mcb_offset = cfg->cfg_last_idx + 1;
1349         body->mcb_type   = cld->cld_type;
1350         body->mcb_bits   = PAGE_CACHE_SHIFT;
1351         body->mcb_units  = nrpages;
1352
1353         /* allocate bulk transfer descriptor */
1354         desc = ptlrpc_prep_bulk_imp(req, nrpages, 1, BULK_PUT_SINK,
1355                                     MGS_BULK_PORTAL);
1356         if (desc == NULL) {
1357                 rc = -ENOMEM;
1358                 goto out;
1359         }
1360
1361         for (i = 0; i < nrpages; i++)
1362                 ptlrpc_prep_bulk_page_pin(desc, pages[i], 0, PAGE_CACHE_SIZE);
1363
1364         ptlrpc_request_set_replen(req);
1365         rc = ptlrpc_queue_wait(req);
1366         if (rc)
1367                 goto out;
1368
1369         res = req_capsule_server_get(&req->rq_pill, &RMF_MGS_CONFIG_RES);
1370         if (res->mcr_size < res->mcr_offset) {
1371                 rc = -EINVAL;
1372                 goto out;
1373         }
1374
1375         /* always update the index even though it might have errors with
1376          * handling the recover logs */
1377         cfg->cfg_last_idx = res->mcr_offset;
1378         eof = res->mcr_offset == res->mcr_size;
1379
1380         CDEBUG(D_INFO, "Latest version %lld, more %d.\n",
1381                res->mcr_offset, eof == false);
1382
1383         ealen = sptlrpc_cli_unwrap_bulk_read(req, req->rq_bulk, 0);
1384         if (ealen < 0) {
1385                 rc = ealen;
1386                 goto out;
1387         }
1388
1389         if (ealen > nrpages << PAGE_CACHE_SHIFT) {
1390                 rc = -EINVAL;
1391                 goto out;
1392         }
1393
1394         if (ealen == 0) { /* no logs transferred */
1395                 if (!eof)
1396                         rc = -EINVAL;
1397                 goto out;
1398         }
1399
1400         mne_swab = !!ptlrpc_rep_need_swab(req);
1401 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 2, 50, 0)
1402         /* This import flag means the server did an extra swab of IR MNE
1403          * records (fixed in LU-1252), reverse it here if needed. LU-1644 */
1404         if (unlikely(req->rq_import->imp_need_mne_swab))
1405                 mne_swab = !mne_swab;
1406 #else
1407 #warning "LU-1644: Remove old OBD_CONNECT_MNE_SWAB fixup and imp_need_mne_swab"
1408 #endif
1409
1410         for (i = 0; i < nrpages && ealen > 0; i++) {
1411                 int rc2;
1412                 void *ptr;
1413
1414                 ptr = kmap(pages[i]);
1415                 rc2 = mgc_apply_recover_logs(obd, cld, res->mcr_offset, ptr,
1416                                              min_t(int, ealen, PAGE_CACHE_SIZE),
1417                                              mne_swab);
1418                 kunmap(pages[i]);
1419                 if (rc2 < 0) {
1420                         CWARN("Process recover log %s error %d\n",
1421                               cld->cld_logname, rc2);
1422                         break;
1423                 }
1424
1425                 ealen -= PAGE_CACHE_SIZE;
1426         }
1427
1428 out:
1429         if (req)
1430                 ptlrpc_req_finished(req);
1431
1432         if (rc == 0 && !eof)
1433                 goto again;
1434
1435         if (pages) {
1436                 for (i = 0; i < nrpages; i++) {
1437                         if (pages[i] == NULL)
1438                                 break;
1439                         __free_page(pages[i]);
1440                 }
1441                 kfree(pages);
1442         }
1443         return rc;
1444 }
1445
1446 /* local_only means it cannot get remote llogs */
1447 static int mgc_process_cfg_log(struct obd_device *mgc,
1448                                struct config_llog_data *cld, int local_only)
1449 {
1450         struct llog_ctxt        *ctxt;
1451         struct lustre_sb_info   *lsi = NULL;
1452         int                      rc = 0;
1453         bool                     sptlrpc_started = false;
1454         struct lu_env           *env;
1455
1456         LASSERT(cld);
1457         LASSERT(mutex_is_locked(&cld->cld_lock));
1458
1459         /*
1460          * local copy of sptlrpc log is controlled elsewhere, don't try to
1461          * read it up here.
1462          */
1463         if (cld_is_sptlrpc(cld) && local_only)
1464                 return 0;
1465
1466         if (cld->cld_cfg.cfg_sb)
1467                 lsi = s2lsi(cld->cld_cfg.cfg_sb);
1468
1469         env = kzalloc(sizeof(*env), GFP_KERNEL);
1470         if (!env)
1471                 return -ENOMEM;
1472
1473         rc = lu_env_init(env, LCT_MG_THREAD);
1474         if (rc)
1475                 goto out_free;
1476
1477         ctxt = llog_get_context(mgc, LLOG_CONFIG_REPL_CTXT);
1478         LASSERT(ctxt);
1479
1480         if (local_only) /* no local log at client side */ {
1481                 rc = -EIO;
1482                 goto out_pop;
1483         }
1484
1485         if (cld_is_sptlrpc(cld)) {
1486                 sptlrpc_conf_log_update_begin(cld->cld_logname);
1487                 sptlrpc_started = true;
1488         }
1489
1490         /* logname and instance info should be the same, so use our
1491          * copy of the instance for the update.  The cfg_last_idx will
1492          * be updated here. */
1493         rc = class_config_parse_llog(env, ctxt, cld->cld_logname,
1494                                      &cld->cld_cfg);
1495
1496 out_pop:
1497         __llog_ctxt_put(env, ctxt);
1498
1499         /*
1500          * update settings on existing OBDs. doing it inside
1501          * of llog_process_lock so no device is attaching/detaching
1502          * in parallel.
1503          * the logname must be <fsname>-sptlrpc
1504          */
1505         if (sptlrpc_started) {
1506                 LASSERT(cld_is_sptlrpc(cld));
1507                 sptlrpc_conf_log_update_end(cld->cld_logname);
1508                 class_notify_sptlrpc_conf(cld->cld_logname,
1509                                           strlen(cld->cld_logname) -
1510                                           strlen("-sptlrpc"));
1511         }
1512
1513         lu_env_fini(env);
1514 out_free:
1515         kfree(env);
1516         return rc;
1517 }
1518
1519 /** Get a config log from the MGS and process it.
1520  * This func is called for both clients and servers.
1521  * Copy the log locally before parsing it if appropriate (non-MGS server)
1522  */
1523 int mgc_process_log(struct obd_device *mgc, struct config_llog_data *cld)
1524 {
1525         struct lustre_handle lockh = { 0 };
1526         __u64 flags = LDLM_FL_NO_LRU;
1527         int rc = 0, rcl;
1528
1529         LASSERT(cld);
1530
1531         /* I don't want multiple processes running process_log at once --
1532            sounds like badness.  It actually might be fine, as long as
1533            we're not trying to update from the same log
1534            simultaneously (in which case we should use a per-log sem.) */
1535         mutex_lock(&cld->cld_lock);
1536         if (cld->cld_stopping) {
1537                 mutex_unlock(&cld->cld_lock);
1538                 return 0;
1539         }
1540
1541         OBD_FAIL_TIMEOUT(OBD_FAIL_MGC_PAUSE_PROCESS_LOG, 20);
1542
1543         CDEBUG(D_MGC, "Process log %s:%p from %d\n", cld->cld_logname,
1544                cld->cld_cfg.cfg_instance, cld->cld_cfg.cfg_last_idx + 1);
1545
1546         /* Get the cfg lock on the llog */
1547         rcl = mgc_enqueue(mgc->u.cli.cl_mgc_mgsexp, NULL, LDLM_PLAIN, NULL,
1548                           LCK_CR, &flags, NULL, NULL, NULL,
1549                           cld, 0, NULL, &lockh);
1550         if (rcl == 0) {
1551                 /* Get the cld, it will be released in mgc_blocking_ast. */
1552                 config_log_get(cld);
1553                 rc = ldlm_lock_set_data(&lockh, (void *)cld);
1554                 LASSERT(rc == 0);
1555         } else {
1556                 CDEBUG(D_MGC, "Can't get cfg lock: %d\n", rcl);
1557
1558                 /* mark cld_lostlock so that it will requeue
1559                  * after MGC becomes available. */
1560                 cld->cld_lostlock = 1;
1561                 /* Get extra reference, it will be put in requeue thread */
1562                 config_log_get(cld);
1563         }
1564
1565         if (cld_is_recover(cld)) {
1566                 rc = 0; /* this is not a fatal error for recover log */
1567                 if (rcl == 0)
1568                         rc = mgc_process_recover_log(mgc, cld);
1569         } else {
1570                 rc = mgc_process_cfg_log(mgc, cld, rcl != 0);
1571         }
1572
1573         CDEBUG(D_MGC, "%s: configuration from log '%s' %sed (%d).\n",
1574                mgc->obd_name, cld->cld_logname, rc ? "fail" : "succeed", rc);
1575
1576         mutex_unlock(&cld->cld_lock);
1577
1578         /* Now drop the lock so MGS can revoke it */
1579         if (!rcl)
1580                 ldlm_lock_decref(&lockh, LCK_CR);
1581
1582         return rc;
1583 }
1584
1585 /** Called from lustre_process_log.
1586  * LCFG_LOG_START gets the config log from the MGS, processes it to start
1587  * any services, and adds it to the list logs to watch (follow).
1588  */
1589 static int mgc_process_config(struct obd_device *obd, u32 len, void *buf)
1590 {
1591         struct lustre_cfg *lcfg = buf;
1592         struct config_llog_instance *cfg = NULL;
1593         char *logname;
1594         int rc = 0;
1595
1596         switch (lcfg->lcfg_command) {
1597         case LCFG_LOV_ADD_OBD: {
1598                 /* Overloading this cfg command: register a new target */
1599                 struct mgs_target_info *mti;
1600
1601                 if (LUSTRE_CFG_BUFLEN(lcfg, 1) !=
1602                     sizeof(struct mgs_target_info)) {
1603                         rc = -EINVAL;
1604                         goto out;
1605                 }
1606
1607                 mti = (struct mgs_target_info *)lustre_cfg_buf(lcfg, 1);
1608                 CDEBUG(D_MGC, "add_target %s %#x\n",
1609                        mti->mti_svname, mti->mti_flags);
1610                 rc = mgc_target_register(obd->u.cli.cl_mgc_mgsexp, mti);
1611                 break;
1612         }
1613         case LCFG_LOV_DEL_OBD:
1614                 /* Unregister has no meaning at the moment. */
1615                 CERROR("lov_del_obd unimplemented\n");
1616                 rc = -ENOSYS;
1617                 break;
1618         case LCFG_SPTLRPC_CONF: {
1619                 rc = sptlrpc_process_config(lcfg);
1620                 break;
1621         }
1622         case LCFG_LOG_START: {
1623                 struct config_llog_data *cld;
1624                 struct super_block *sb;
1625
1626                 logname = lustre_cfg_string(lcfg, 1);
1627                 cfg = (struct config_llog_instance *)lustre_cfg_buf(lcfg, 2);
1628                 sb = *(struct super_block **)lustre_cfg_buf(lcfg, 3);
1629
1630                 CDEBUG(D_MGC, "parse_log %s from %d\n", logname,
1631                        cfg->cfg_last_idx);
1632
1633                 /* We're only called through here on the initial mount */
1634                 rc = config_log_add(obd, logname, cfg, sb);
1635                 if (rc)
1636                         break;
1637                 cld = config_log_find(logname, cfg);
1638                 if (cld == NULL) {
1639                         rc = -ENOENT;
1640                         break;
1641                 }
1642
1643                 /* COMPAT_146 */
1644                 /* FIXME only set this for old logs!  Right now this forces
1645                    us to always skip the "inside markers" check */
1646                 cld->cld_cfg.cfg_flags |= CFG_F_COMPAT146;
1647
1648                 rc = mgc_process_log(obd, cld);
1649                 if (rc == 0 && cld->cld_recover != NULL) {
1650                         if (OCD_HAS_FLAG(&obd->u.cli.cl_import->
1651                                          imp_connect_data, IMP_RECOV)) {
1652                                 rc = mgc_process_log(obd, cld->cld_recover);
1653                         } else {
1654                                 struct config_llog_data *cir = cld->cld_recover;
1655
1656                                 cld->cld_recover = NULL;
1657                                 config_log_put(cir);
1658                         }
1659                         if (rc)
1660                                 CERROR("Cannot process recover llog %d\n", rc);
1661                 }
1662
1663                 if (rc == 0 && cld->cld_params != NULL) {
1664                         rc = mgc_process_log(obd, cld->cld_params);
1665                         if (rc == -ENOENT) {
1666                                 CDEBUG(D_MGC,
1667                                        "There is no params config file yet\n");
1668                                 rc = 0;
1669                         }
1670                         /* params log is optional */
1671                         if (rc)
1672                                 CERROR(
1673                                        "%s: can't process params llog: rc = %d\n",
1674                                        obd->obd_name, rc);
1675                 }
1676                 config_log_put(cld);
1677
1678                 break;
1679         }
1680         case LCFG_LOG_END: {
1681                 logname = lustre_cfg_string(lcfg, 1);
1682
1683                 if (lcfg->lcfg_bufcount >= 2)
1684                         cfg = (struct config_llog_instance *)lustre_cfg_buf(
1685                                 lcfg, 2);
1686                 rc = config_log_end(logname, cfg);
1687                 break;
1688         }
1689         default: {
1690                 CERROR("Unknown command: %d\n", lcfg->lcfg_command);
1691                 rc = -EINVAL;
1692                 goto out;
1693
1694         }
1695         }
1696 out:
1697         return rc;
1698 }
1699
1700 static struct obd_ops mgc_obd_ops = {
1701         .o_owner        = THIS_MODULE,
1702         .o_setup        = mgc_setup,
1703         .o_precleanup   = mgc_precleanup,
1704         .o_cleanup      = mgc_cleanup,
1705         .o_add_conn     = client_import_add_conn,
1706         .o_del_conn     = client_import_del_conn,
1707         .o_connect      = client_connect_import,
1708         .o_disconnect   = client_disconnect_export,
1709         /* .o_enqueue      = mgc_enqueue, */
1710         /* .o_iocontrol    = mgc_iocontrol, */
1711         .o_set_info_async = mgc_set_info_async,
1712         .o_get_info       = mgc_get_info,
1713         .o_import_event = mgc_import_event,
1714         .o_process_config = mgc_process_config,
1715 };
1716
1717 static int __init mgc_init(void)
1718 {
1719         return class_register_type(&mgc_obd_ops, NULL,
1720                                    LUSTRE_MGC_NAME, NULL);
1721 }
1722
1723 static void /*__exit*/ mgc_exit(void)
1724 {
1725         class_unregister_type(LUSTRE_MGC_NAME);
1726 }
1727
1728 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
1729 MODULE_DESCRIPTION("Lustre Management Client");
1730 MODULE_LICENSE("GPL");
1731
1732 module_init(mgc_init);
1733 module_exit(mgc_exit);