drbd: Convert the generic netlink interface to accept connection endpoints
[firefly-linux-kernel-4.4.55.git] / drivers / block / drbd / drbd_nl.c
1 /*
2    drbd_nl.c
3
4    This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
5
6    Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
7    Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
8    Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
9
10    drbd is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2, or (at your option)
13    any later version.
14
15    drbd is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with drbd; see the file COPYING.  If not, write to
22    the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24  */
25
26 #include <linux/module.h>
27 #include <linux/drbd.h>
28 #include <linux/in.h>
29 #include <linux/fs.h>
30 #include <linux/file.h>
31 #include <linux/slab.h>
32 #include <linux/blkpg.h>
33 #include <linux/cpumask.h>
34 #include "drbd_int.h"
35 #include "drbd_req.h"
36 #include "drbd_wrappers.h"
37 #include <asm/unaligned.h>
38 #include <linux/drbd_limits.h>
39 #include <linux/kthread.h>
40
41 #include <net/genetlink.h>
42
43 /* .doit */
44 // int drbd_adm_create_resource(struct sk_buff *skb, struct genl_info *info);
45 // int drbd_adm_delete_resource(struct sk_buff *skb, struct genl_info *info);
46
47 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info);
48 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info);
49
50 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info);
51 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info);
52 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info);
53
54 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info);
55 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info);
56 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info);
57 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info);
58 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info);
59 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info);
60 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info);
61 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info);
62 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info);
63 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info);
64 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info);
65 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info);
66 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info);
67 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info);
68 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info);
69 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info);
70 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info);
71 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info);
72 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info);
73 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info);
74 /* .dumpit */
75 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb);
76
77 #include <linux/drbd_genl_api.h>
78 #include "drbd_nla.h"
79 #include <linux/genl_magic_func.h>
80
81 /* used blkdev_get_by_path, to claim our meta data device(s) */
82 static char *drbd_m_holder = "Hands off! this is DRBD's meta data device.";
83
84 /* Configuration is strictly serialized, because generic netlink message
85  * processing is strictly serialized by the genl_lock().
86  * Which means we can use one static global drbd_config_context struct.
87  */
88 static struct drbd_config_context {
89         /* assigned from drbd_genlmsghdr */
90         unsigned int minor;
91         /* assigned from request attributes, if present */
92         unsigned int volume;
93 #define VOLUME_UNSPECIFIED              (-1U)
94         /* pointer into the request skb,
95          * limited lifetime! */
96         char *resource_name;
97         struct nlattr *my_addr;
98         struct nlattr *peer_addr;
99
100         /* reply buffer */
101         struct sk_buff *reply_skb;
102         /* pointer into reply buffer */
103         struct drbd_genlmsghdr *reply_dh;
104         /* resolved from attributes, if possible */
105         struct drbd_conf *mdev;
106         struct drbd_tconn *tconn;
107 } adm_ctx;
108
109 static void drbd_adm_send_reply(struct sk_buff *skb, struct genl_info *info)
110 {
111         genlmsg_end(skb, genlmsg_data(nlmsg_data(nlmsg_hdr(skb))));
112         if (genlmsg_reply(skb, info))
113                 printk(KERN_ERR "drbd: error sending genl reply\n");
114 }
115
116 /* Used on a fresh "drbd_adm_prepare"d reply_skb, this cannot fail: The only
117  * reason it could fail was no space in skb, and there are 4k available. */
118 int drbd_msg_put_info(const char *info)
119 {
120         struct sk_buff *skb = adm_ctx.reply_skb;
121         struct nlattr *nla;
122         int err = -EMSGSIZE;
123
124         if (!info || !info[0])
125                 return 0;
126
127         nla = nla_nest_start(skb, DRBD_NLA_CFG_REPLY);
128         if (!nla)
129                 return err;
130
131         err = nla_put_string(skb, T_info_text, info);
132         if (err) {
133                 nla_nest_cancel(skb, nla);
134                 return err;
135         } else
136                 nla_nest_end(skb, nla);
137         return 0;
138 }
139
140 /* This would be a good candidate for a "pre_doit" hook,
141  * and per-family private info->pointers.
142  * But we need to stay compatible with older kernels.
143  * If it returns successfully, adm_ctx members are valid.
144  */
145 #define DRBD_ADM_NEED_MINOR     1
146 #define DRBD_ADM_NEED_RESOURCE  2
147 #define DRBD_ADM_NEED_CONNECTION 4
148 static int drbd_adm_prepare(struct sk_buff *skb, struct genl_info *info,
149                 unsigned flags)
150 {
151         struct drbd_genlmsghdr *d_in = info->userhdr;
152         const u8 cmd = info->genlhdr->cmd;
153         int err;
154
155         memset(&adm_ctx, 0, sizeof(adm_ctx));
156
157         /* genl_rcv_msg only checks for CAP_NET_ADMIN on "GENL_ADMIN_PERM" :( */
158         if (cmd != DRBD_ADM_GET_STATUS
159         && security_netlink_recv(skb, CAP_SYS_ADMIN))
160                return -EPERM;
161
162         adm_ctx.reply_skb = genlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
163         if (!adm_ctx.reply_skb) {
164                 err = -ENOMEM;
165                 goto fail;
166         }
167
168         adm_ctx.reply_dh = genlmsg_put_reply(adm_ctx.reply_skb,
169                                         info, &drbd_genl_family, 0, cmd);
170         /* put of a few bytes into a fresh skb of >= 4k will always succeed.
171          * but anyways */
172         if (!adm_ctx.reply_dh) {
173                 err = -ENOMEM;
174                 goto fail;
175         }
176
177         adm_ctx.reply_dh->minor = d_in->minor;
178         adm_ctx.reply_dh->ret_code = NO_ERROR;
179
180         adm_ctx.volume = VOLUME_UNSPECIFIED;
181         if (info->attrs[DRBD_NLA_CFG_CONTEXT]) {
182                 struct nlattr *nla;
183                 /* parse and validate only */
184                 err = drbd_cfg_context_from_attrs(NULL, info);
185                 if (err)
186                         goto fail;
187
188                 /* It was present, and valid,
189                  * copy it over to the reply skb. */
190                 err = nla_put_nohdr(adm_ctx.reply_skb,
191                                 info->attrs[DRBD_NLA_CFG_CONTEXT]->nla_len,
192                                 info->attrs[DRBD_NLA_CFG_CONTEXT]);
193                 if (err)
194                         goto fail;
195
196                 /* and assign stuff to the global adm_ctx */
197                 nla = nested_attr_tb[__nla_type(T_ctx_volume)];
198                 if (nla)
199                         adm_ctx.volume = nla_get_u32(nla);
200                 nla = nested_attr_tb[__nla_type(T_ctx_resource_name)];
201                 if (nla)
202                         adm_ctx.resource_name = nla_data(nla);
203                 adm_ctx.my_addr = nested_attr_tb[__nla_type(T_ctx_my_addr)];
204                 adm_ctx.peer_addr = nested_attr_tb[__nla_type(T_ctx_peer_addr)];
205                 if ((adm_ctx.my_addr &&
206                      nla_len(adm_ctx.my_addr) > sizeof(adm_ctx.tconn->my_addr)) ||
207                     (adm_ctx.peer_addr &&
208                      nla_len(adm_ctx.peer_addr) > sizeof(adm_ctx.tconn->peer_addr))) {
209                         err = -EINVAL;
210                         goto fail;
211                 }
212         }
213
214         adm_ctx.minor = d_in->minor;
215         adm_ctx.mdev = minor_to_mdev(d_in->minor);
216         adm_ctx.tconn = conn_get_by_name(adm_ctx.resource_name);
217
218         if (!adm_ctx.mdev && (flags & DRBD_ADM_NEED_MINOR)) {
219                 drbd_msg_put_info("unknown minor");
220                 return ERR_MINOR_INVALID;
221         }
222         if (!adm_ctx.tconn && (flags & DRBD_ADM_NEED_RESOURCE)) {
223                 drbd_msg_put_info("unknown resource");
224                 return ERR_INVALID_REQUEST;
225         }
226
227         if (flags & DRBD_ADM_NEED_CONNECTION) {
228                 if (adm_ctx.tconn && !(flags & DRBD_ADM_NEED_RESOURCE)) {
229                         drbd_msg_put_info("no resource name expected");
230                         return ERR_INVALID_REQUEST;
231                 }
232                 if (adm_ctx.mdev) {
233                         drbd_msg_put_info("no minor number expected");
234                         return ERR_INVALID_REQUEST;
235                 }
236                 if (adm_ctx.my_addr && adm_ctx.peer_addr)
237                         adm_ctx.tconn = conn_get_by_addrs(nla_data(adm_ctx.my_addr),
238                                                           nla_len(adm_ctx.my_addr),
239                                                           nla_data(adm_ctx.peer_addr),
240                                                           nla_len(adm_ctx.peer_addr));
241                 if (!adm_ctx.tconn) {
242                         drbd_msg_put_info("unknown connection");
243                         return ERR_INVALID_REQUEST;
244                 }
245         }
246
247         /* some more paranoia, if the request was over-determined */
248         if (adm_ctx.mdev && adm_ctx.tconn &&
249             adm_ctx.mdev->tconn != adm_ctx.tconn) {
250                 pr_warning("request: minor=%u, resource=%s; but that minor belongs to connection %s\n",
251                                 adm_ctx.minor, adm_ctx.resource_name,
252                                 adm_ctx.mdev->tconn->name);
253                 drbd_msg_put_info("minor exists in different resource");
254                 return ERR_INVALID_REQUEST;
255         }
256         if (adm_ctx.mdev &&
257             adm_ctx.volume != VOLUME_UNSPECIFIED &&
258             adm_ctx.volume != adm_ctx.mdev->vnr) {
259                 pr_warning("request: minor=%u, volume=%u; but that minor is volume %u in %s\n",
260                                 adm_ctx.minor, adm_ctx.volume,
261                                 adm_ctx.mdev->vnr, adm_ctx.mdev->tconn->name);
262                 drbd_msg_put_info("minor exists as different volume");
263                 return ERR_INVALID_REQUEST;
264         }
265
266         return NO_ERROR;
267
268 fail:
269         nlmsg_free(adm_ctx.reply_skb);
270         adm_ctx.reply_skb = NULL;
271         return err;
272 }
273
274 static int drbd_adm_finish(struct genl_info *info, int retcode)
275 {
276         struct nlattr *nla;
277         const char *resource_name = NULL;
278
279         if (adm_ctx.tconn) {
280                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
281                 adm_ctx.tconn = NULL;
282         }
283
284         if (!adm_ctx.reply_skb)
285                 return -ENOMEM;
286
287         adm_ctx.reply_dh->ret_code = retcode;
288
289         nla = info->attrs[DRBD_NLA_CFG_CONTEXT];
290         if (nla) {
291                 int maxtype = ARRAY_SIZE(drbd_cfg_context_nl_policy) - 1;
292                 nla = drbd_nla_find_nested(maxtype, nla, __nla_type(T_ctx_resource_name));
293                 if (nla && !IS_ERR(nla))
294                         resource_name = nla_data(nla);
295         }
296
297         drbd_adm_send_reply(adm_ctx.reply_skb, info);
298         return 0;
299 }
300
301 static void setup_khelper_env(struct drbd_tconn *tconn, char **envp)
302 {
303         char *afs;
304
305         /* FIXME: A future version will not allow this case. */
306         if (tconn->my_addr_len == 0 || tconn->peer_addr_len == 0)
307                 return;
308
309         switch (((struct sockaddr *)&tconn->peer_addr)->sa_family) {
310         case AF_INET6:
311                 afs = "ipv6";
312                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI6",
313                          &((struct sockaddr_in6 *)&tconn->peer_addr)->sin6_addr);
314                 break;
315         case AF_INET:
316                 afs = "ipv4";
317                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
318                          &((struct sockaddr_in *)&tconn->peer_addr)->sin_addr);
319                 break;
320         default:
321                 afs = "ssocks";
322                 snprintf(envp[4], 60, "DRBD_PEER_ADDRESS=%pI4",
323                          &((struct sockaddr_in *)&tconn->peer_addr)->sin_addr);
324         }
325         snprintf(envp[3], 20, "DRBD_PEER_AF=%s", afs);
326 }
327
328 int drbd_khelper(struct drbd_conf *mdev, char *cmd)
329 {
330         char *envp[] = { "HOME=/",
331                         "TERM=linux",
332                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
333                          (char[20]) { }, /* address family */
334                          (char[60]) { }, /* address */
335                         NULL };
336         char mb[12];
337         char *argv[] = {usermode_helper, cmd, mb, NULL };
338         struct sib_info sib;
339         int ret;
340
341         snprintf(mb, 12, "minor-%d", mdev_to_minor(mdev));
342         setup_khelper_env(mdev->tconn, envp);
343
344         /* The helper may take some time.
345          * write out any unsynced meta data changes now */
346         drbd_md_sync(mdev);
347
348         dev_info(DEV, "helper command: %s %s %s\n", usermode_helper, cmd, mb);
349         sib.sib_reason = SIB_HELPER_PRE;
350         sib.helper_name = cmd;
351         drbd_bcast_event(mdev, &sib);
352         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
353         if (ret)
354                 dev_warn(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
355                                 usermode_helper, cmd, mb,
356                                 (ret >> 8) & 0xff, ret);
357         else
358                 dev_info(DEV, "helper command: %s %s %s exit code %u (0x%x)\n",
359                                 usermode_helper, cmd, mb,
360                                 (ret >> 8) & 0xff, ret);
361         sib.sib_reason = SIB_HELPER_POST;
362         sib.helper_exit_code = ret;
363         drbd_bcast_event(mdev, &sib);
364
365         if (ret < 0) /* Ignore any ERRNOs we got. */
366                 ret = 0;
367
368         return ret;
369 }
370
371 static void conn_md_sync(struct drbd_tconn *tconn)
372 {
373         struct drbd_conf *mdev;
374         int vnr;
375
376         rcu_read_lock();
377         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
378                 kref_get(&mdev->kref);
379                 rcu_read_unlock();
380                 drbd_md_sync(mdev);
381                 kref_put(&mdev->kref, &drbd_minor_destroy);
382                 rcu_read_lock();
383         }
384         rcu_read_unlock();
385 }
386
387 int conn_khelper(struct drbd_tconn *tconn, char *cmd)
388 {
389         char *envp[] = { "HOME=/",
390                         "TERM=linux",
391                         "PATH=/sbin:/usr/sbin:/bin:/usr/bin",
392                          (char[20]) { }, /* address family */
393                          (char[60]) { }, /* address */
394                         NULL };
395         char *argv[] = {usermode_helper, cmd, tconn->name, NULL };
396         int ret;
397
398         setup_khelper_env(tconn, envp);
399         conn_md_sync(tconn);
400
401         conn_info(tconn, "helper command: %s %s %s\n", usermode_helper, cmd, tconn->name);
402         /* TODO: conn_bcast_event() ?? */
403
404         ret = call_usermodehelper(usermode_helper, argv, envp, 1);
405         if (ret)
406                 conn_warn(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
407                           usermode_helper, cmd, tconn->name,
408                           (ret >> 8) & 0xff, ret);
409         else
410                 conn_info(tconn, "helper command: %s %s %s exit code %u (0x%x)\n",
411                           usermode_helper, cmd, tconn->name,
412                           (ret >> 8) & 0xff, ret);
413         /* TODO: conn_bcast_event() ?? */
414
415         if (ret < 0) /* Ignore any ERRNOs we got. */
416                 ret = 0;
417
418         return ret;
419 }
420
421 static enum drbd_fencing_p highest_fencing_policy(struct drbd_tconn *tconn)
422 {
423         enum drbd_fencing_p fp = FP_NOT_AVAIL;
424         struct drbd_conf *mdev;
425         int vnr;
426
427         rcu_read_lock();
428         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
429                 if (get_ldev_if_state(mdev, D_CONSISTENT)) {
430                         fp = max_t(enum drbd_fencing_p, fp,
431                                    rcu_dereference(mdev->ldev->disk_conf)->fencing);
432                         put_ldev(mdev);
433                 }
434         }
435         rcu_read_unlock();
436
437         return fp;
438 }
439
440 bool conn_try_outdate_peer(struct drbd_tconn *tconn)
441 {
442         union drbd_state mask = { };
443         union drbd_state val = { };
444         enum drbd_fencing_p fp;
445         char *ex_to_string;
446         int r;
447
448         if (tconn->cstate >= C_WF_REPORT_PARAMS) {
449                 conn_err(tconn, "Expected cstate < C_WF_REPORT_PARAMS\n");
450                 return false;
451         }
452
453         fp = highest_fencing_policy(tconn);
454         switch (fp) {
455         case FP_NOT_AVAIL:
456                 conn_warn(tconn, "Not fencing peer, I'm not even Consistent myself.\n");
457                 goto out;
458         case FP_DONT_CARE:
459                 return true;
460         default: ;
461         }
462
463         r = conn_khelper(tconn, "fence-peer");
464
465         switch ((r>>8) & 0xff) {
466         case 3: /* peer is inconsistent */
467                 ex_to_string = "peer is inconsistent or worse";
468                 mask.pdsk = D_MASK;
469                 val.pdsk = D_INCONSISTENT;
470                 break;
471         case 4: /* peer got outdated, or was already outdated */
472                 ex_to_string = "peer was fenced";
473                 mask.pdsk = D_MASK;
474                 val.pdsk = D_OUTDATED;
475                 break;
476         case 5: /* peer was down */
477                 if (conn_highest_disk(tconn) == D_UP_TO_DATE) {
478                         /* we will(have) create(d) a new UUID anyways... */
479                         ex_to_string = "peer is unreachable, assumed to be dead";
480                         mask.pdsk = D_MASK;
481                         val.pdsk = D_OUTDATED;
482                 } else {
483                         ex_to_string = "peer unreachable, doing nothing since disk != UpToDate";
484                 }
485                 break;
486         case 6: /* Peer is primary, voluntarily outdate myself.
487                  * This is useful when an unconnected R_SECONDARY is asked to
488                  * become R_PRIMARY, but finds the other peer being active. */
489                 ex_to_string = "peer is active";
490                 conn_warn(tconn, "Peer is primary, outdating myself.\n");
491                 mask.disk = D_MASK;
492                 val.disk = D_OUTDATED;
493                 break;
494         case 7:
495                 if (fp != FP_STONITH)
496                         conn_err(tconn, "fence-peer() = 7 && fencing != Stonith !!!\n");
497                 ex_to_string = "peer was stonithed";
498                 mask.pdsk = D_MASK;
499                 val.pdsk = D_OUTDATED;
500                 break;
501         default:
502                 /* The script is broken ... */
503                 conn_err(tconn, "fence-peer helper broken, returned %d\n", (r>>8)&0xff);
504                 return false; /* Eventually leave IO frozen */
505         }
506
507         conn_info(tconn, "fence-peer helper returned %d (%s)\n",
508                   (r>>8) & 0xff, ex_to_string);
509
510  out:
511
512         /* Not using
513            conn_request_state(tconn, mask, val, CS_VERBOSE);
514            here, because we might were able to re-establish the connection in the
515            meantime. */
516         spin_lock_irq(&tconn->req_lock);
517         if (tconn->cstate < C_WF_REPORT_PARAMS)
518                 _conn_request_state(tconn, mask, val, CS_VERBOSE);
519         spin_unlock_irq(&tconn->req_lock);
520
521         return conn_highest_pdsk(tconn) <= D_OUTDATED;
522 }
523
524 static int _try_outdate_peer_async(void *data)
525 {
526         struct drbd_tconn *tconn = (struct drbd_tconn *)data;
527
528         conn_try_outdate_peer(tconn);
529
530         kref_put(&tconn->kref, &conn_destroy);
531         return 0;
532 }
533
534 void conn_try_outdate_peer_async(struct drbd_tconn *tconn)
535 {
536         struct task_struct *opa;
537
538         kref_get(&tconn->kref);
539         opa = kthread_run(_try_outdate_peer_async, tconn, "drbd_async_h");
540         if (IS_ERR(opa)) {
541                 conn_err(tconn, "out of mem, failed to invoke fence-peer helper\n");
542                 kref_put(&tconn->kref, &conn_destroy);
543         }
544 }
545
546 enum drbd_state_rv
547 drbd_set_role(struct drbd_conf *mdev, enum drbd_role new_role, int force)
548 {
549         const int max_tries = 4;
550         enum drbd_state_rv rv = SS_UNKNOWN_ERROR;
551         struct net_conf *nc;
552         int try = 0;
553         int forced = 0;
554         union drbd_state mask, val;
555
556         if (new_role == R_PRIMARY)
557                 request_ping(mdev->tconn); /* Detect a dead peer ASAP */
558
559         mutex_lock(mdev->state_mutex);
560
561         mask.i = 0; mask.role = R_MASK;
562         val.i  = 0; val.role  = new_role;
563
564         while (try++ < max_tries) {
565                 rv = _drbd_request_state(mdev, mask, val, CS_WAIT_COMPLETE);
566
567                 /* in case we first succeeded to outdate,
568                  * but now suddenly could establish a connection */
569                 if (rv == SS_CW_FAILED_BY_PEER && mask.pdsk != 0) {
570                         val.pdsk = 0;
571                         mask.pdsk = 0;
572                         continue;
573                 }
574
575                 if (rv == SS_NO_UP_TO_DATE_DISK && force &&
576                     (mdev->state.disk < D_UP_TO_DATE &&
577                      mdev->state.disk >= D_INCONSISTENT)) {
578                         mask.disk = D_MASK;
579                         val.disk  = D_UP_TO_DATE;
580                         forced = 1;
581                         continue;
582                 }
583
584                 if (rv == SS_NO_UP_TO_DATE_DISK &&
585                     mdev->state.disk == D_CONSISTENT && mask.pdsk == 0) {
586                         D_ASSERT(mdev->state.pdsk == D_UNKNOWN);
587
588                         if (conn_try_outdate_peer(mdev->tconn)) {
589                                 val.disk = D_UP_TO_DATE;
590                                 mask.disk = D_MASK;
591                         }
592                         continue;
593                 }
594
595                 if (rv == SS_NOTHING_TO_DO)
596                         goto out;
597                 if (rv == SS_PRIMARY_NOP && mask.pdsk == 0) {
598                         if (!conn_try_outdate_peer(mdev->tconn) && force) {
599                                 dev_warn(DEV, "Forced into split brain situation!\n");
600                                 mask.pdsk = D_MASK;
601                                 val.pdsk  = D_OUTDATED;
602
603                         }
604                         continue;
605                 }
606                 if (rv == SS_TWO_PRIMARIES) {
607                         /* Maybe the peer is detected as dead very soon...
608                            retry at most once more in this case. */
609                         int timeo;
610                         rcu_read_lock();
611                         nc = rcu_dereference(mdev->tconn->net_conf);
612                         timeo = nc ? (nc->ping_timeo + 1) * HZ / 10 : 1;
613                         rcu_read_unlock();
614                         schedule_timeout_interruptible(timeo);
615                         if (try < max_tries)
616                                 try = max_tries - 1;
617                         continue;
618                 }
619                 if (rv < SS_SUCCESS) {
620                         rv = _drbd_request_state(mdev, mask, val,
621                                                 CS_VERBOSE + CS_WAIT_COMPLETE);
622                         if (rv < SS_SUCCESS)
623                                 goto out;
624                 }
625                 break;
626         }
627
628         if (rv < SS_SUCCESS)
629                 goto out;
630
631         if (forced)
632                 dev_warn(DEV, "Forced to consider local data as UpToDate!\n");
633
634         /* Wait until nothing is on the fly :) */
635         wait_event(mdev->misc_wait, atomic_read(&mdev->ap_pending_cnt) == 0);
636
637         if (new_role == R_SECONDARY) {
638                 set_disk_ro(mdev->vdisk, true);
639                 if (get_ldev(mdev)) {
640                         mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
641                         put_ldev(mdev);
642                 }
643         } else {
644                 mutex_lock(&mdev->tconn->conf_update);
645                 nc = mdev->tconn->net_conf;
646                 if (nc)
647                         nc->discard_my_data = 0; /* without copy; single bit op is atomic */
648                 mutex_unlock(&mdev->tconn->conf_update);
649
650                 set_disk_ro(mdev->vdisk, false);
651                 if (get_ldev(mdev)) {
652                         if (((mdev->state.conn < C_CONNECTED ||
653                                mdev->state.pdsk <= D_FAILED)
654                               && mdev->ldev->md.uuid[UI_BITMAP] == 0) || forced)
655                                 drbd_uuid_new_current(mdev);
656
657                         mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
658                         put_ldev(mdev);
659                 }
660         }
661
662         /* writeout of activity log covered areas of the bitmap
663          * to stable storage done in after state change already */
664
665         if (mdev->state.conn >= C_WF_REPORT_PARAMS) {
666                 /* if this was forced, we should consider sync */
667                 if (forced)
668                         drbd_send_uuids(mdev);
669                 drbd_send_state(mdev);
670         }
671
672         drbd_md_sync(mdev);
673
674         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
675 out:
676         mutex_unlock(mdev->state_mutex);
677         return rv;
678 }
679
680 static const char *from_attrs_err_to_txt(int err)
681 {
682         return  err == -ENOMSG ? "required attribute missing" :
683                 err == -EOPNOTSUPP ? "unknown mandatory attribute" :
684                 err == -EEXIST ? "can not change invariant setting" :
685                 "invalid attribute value";
686 }
687
688 int drbd_adm_set_role(struct sk_buff *skb, struct genl_info *info)
689 {
690         struct set_role_parms parms;
691         int err;
692         enum drbd_ret_code retcode;
693
694         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
695         if (!adm_ctx.reply_skb)
696                 return retcode;
697         if (retcode != NO_ERROR)
698                 goto out;
699
700         memset(&parms, 0, sizeof(parms));
701         if (info->attrs[DRBD_NLA_SET_ROLE_PARMS]) {
702                 err = set_role_parms_from_attrs(&parms, info);
703                 if (err) {
704                         retcode = ERR_MANDATORY_TAG;
705                         drbd_msg_put_info(from_attrs_err_to_txt(err));
706                         goto out;
707                 }
708         }
709
710         if (info->genlhdr->cmd == DRBD_ADM_PRIMARY)
711                 retcode = drbd_set_role(adm_ctx.mdev, R_PRIMARY, parms.assume_uptodate);
712         else
713                 retcode = drbd_set_role(adm_ctx.mdev, R_SECONDARY, 0);
714 out:
715         drbd_adm_finish(info, retcode);
716         return 0;
717 }
718
719 /* initializes the md.*_offset members, so we are able to find
720  * the on disk meta data */
721 static void drbd_md_set_sector_offsets(struct drbd_conf *mdev,
722                                        struct drbd_backing_dev *bdev)
723 {
724         sector_t md_size_sect = 0;
725         int meta_dev_idx;
726
727         rcu_read_lock();
728         meta_dev_idx = rcu_dereference(bdev->disk_conf)->meta_dev_idx;
729
730         switch (meta_dev_idx) {
731         default:
732                 /* v07 style fixed size indexed meta data */
733                 bdev->md.md_size_sect = MD_RESERVED_SECT;
734                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
735                 bdev->md.al_offset = MD_AL_OFFSET;
736                 bdev->md.bm_offset = MD_BM_OFFSET;
737                 break;
738         case DRBD_MD_INDEX_FLEX_EXT:
739                 /* just occupy the full device; unit: sectors */
740                 bdev->md.md_size_sect = drbd_get_capacity(bdev->md_bdev);
741                 bdev->md.md_offset = 0;
742                 bdev->md.al_offset = MD_AL_OFFSET;
743                 bdev->md.bm_offset = MD_BM_OFFSET;
744                 break;
745         case DRBD_MD_INDEX_INTERNAL:
746         case DRBD_MD_INDEX_FLEX_INT:
747                 bdev->md.md_offset = drbd_md_ss__(mdev, bdev);
748                 /* al size is still fixed */
749                 bdev->md.al_offset = -MD_AL_SECTORS;
750                 /* we need (slightly less than) ~ this much bitmap sectors: */
751                 md_size_sect = drbd_get_capacity(bdev->backing_bdev);
752                 md_size_sect = ALIGN(md_size_sect, BM_SECT_PER_EXT);
753                 md_size_sect = BM_SECT_TO_EXT(md_size_sect);
754                 md_size_sect = ALIGN(md_size_sect, 8);
755
756                 /* plus the "drbd meta data super block",
757                  * and the activity log; */
758                 md_size_sect += MD_BM_OFFSET;
759
760                 bdev->md.md_size_sect = md_size_sect;
761                 /* bitmap offset is adjusted by 'super' block size */
762                 bdev->md.bm_offset   = -md_size_sect + MD_AL_OFFSET;
763                 break;
764         }
765         rcu_read_unlock();
766 }
767
768 /* input size is expected to be in KB */
769 char *ppsize(char *buf, unsigned long long size)
770 {
771         /* Needs 9 bytes at max including trailing NUL:
772          * -1ULL ==> "16384 EB" */
773         static char units[] = { 'K', 'M', 'G', 'T', 'P', 'E' };
774         int base = 0;
775         while (size >= 10000 && base < sizeof(units)-1) {
776                 /* shift + round */
777                 size = (size >> 10) + !!(size & (1<<9));
778                 base++;
779         }
780         sprintf(buf, "%u %cB", (unsigned)size, units[base]);
781
782         return buf;
783 }
784
785 /* there is still a theoretical deadlock when called from receiver
786  * on an D_INCONSISTENT R_PRIMARY:
787  *  remote READ does inc_ap_bio, receiver would need to receive answer
788  *  packet from remote to dec_ap_bio again.
789  *  receiver receive_sizes(), comes here,
790  *  waits for ap_bio_cnt == 0. -> deadlock.
791  * but this cannot happen, actually, because:
792  *  R_PRIMARY D_INCONSISTENT, and peer's disk is unreachable
793  *  (not connected, or bad/no disk on peer):
794  *  see drbd_fail_request_early, ap_bio_cnt is zero.
795  *  R_PRIMARY D_INCONSISTENT, and C_SYNC_TARGET:
796  *  peer may not initiate a resize.
797  */
798 /* Note these are not to be confused with
799  * drbd_adm_suspend_io/drbd_adm_resume_io,
800  * which are (sub) state changes triggered by admin (drbdsetup),
801  * and can be long lived.
802  * This changes an mdev->flag, is triggered by drbd internals,
803  * and should be short-lived. */
804 void drbd_suspend_io(struct drbd_conf *mdev)
805 {
806         set_bit(SUSPEND_IO, &mdev->flags);
807         if (drbd_suspended(mdev))
808                 return;
809         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_bio_cnt));
810 }
811
812 void drbd_resume_io(struct drbd_conf *mdev)
813 {
814         clear_bit(SUSPEND_IO, &mdev->flags);
815         wake_up(&mdev->misc_wait);
816 }
817
818 /**
819  * drbd_determine_dev_size() -  Sets the right device size obeying all constraints
820  * @mdev:       DRBD device.
821  *
822  * Returns 0 on success, negative return values indicate errors.
823  * You should call drbd_md_sync() after calling this function.
824  */
825 enum determine_dev_size drbd_determine_dev_size(struct drbd_conf *mdev, enum dds_flags flags) __must_hold(local)
826 {
827         sector_t prev_first_sect, prev_size; /* previous meta location */
828         sector_t la_size, u_size;
829         sector_t size;
830         char ppb[10];
831
832         int md_moved, la_size_changed;
833         enum determine_dev_size rv = unchanged;
834
835         /* race:
836          * application request passes inc_ap_bio,
837          * but then cannot get an AL-reference.
838          * this function later may wait on ap_bio_cnt == 0. -> deadlock.
839          *
840          * to avoid that:
841          * Suspend IO right here.
842          * still lock the act_log to not trigger ASSERTs there.
843          */
844         drbd_suspend_io(mdev);
845
846         /* no wait necessary anymore, actually we could assert that */
847         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
848
849         prev_first_sect = drbd_md_first_sector(mdev->ldev);
850         prev_size = mdev->ldev->md.md_size_sect;
851         la_size = mdev->ldev->md.la_size_sect;
852
853         /* TODO: should only be some assert here, not (re)init... */
854         drbd_md_set_sector_offsets(mdev, mdev->ldev);
855
856         rcu_read_lock();
857         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
858         rcu_read_unlock();
859         size = drbd_new_dev_size(mdev, mdev->ldev, u_size, flags & DDSF_FORCED);
860
861         if (drbd_get_capacity(mdev->this_bdev) != size ||
862             drbd_bm_capacity(mdev) != size) {
863                 int err;
864                 err = drbd_bm_resize(mdev, size, !(flags & DDSF_NO_RESYNC));
865                 if (unlikely(err)) {
866                         /* currently there is only one error: ENOMEM! */
867                         size = drbd_bm_capacity(mdev)>>1;
868                         if (size == 0) {
869                                 dev_err(DEV, "OUT OF MEMORY! "
870                                     "Could not allocate bitmap!\n");
871                         } else {
872                                 dev_err(DEV, "BM resizing failed. "
873                                     "Leaving size unchanged at size = %lu KB\n",
874                                     (unsigned long)size);
875                         }
876                         rv = dev_size_error;
877                 }
878                 /* racy, see comments above. */
879                 drbd_set_my_capacity(mdev, size);
880                 mdev->ldev->md.la_size_sect = size;
881                 dev_info(DEV, "size = %s (%llu KB)\n", ppsize(ppb, size>>1),
882                      (unsigned long long)size>>1);
883         }
884         if (rv == dev_size_error)
885                 goto out;
886
887         la_size_changed = (la_size != mdev->ldev->md.la_size_sect);
888
889         md_moved = prev_first_sect != drbd_md_first_sector(mdev->ldev)
890                 || prev_size       != mdev->ldev->md.md_size_sect;
891
892         if (la_size_changed || md_moved) {
893                 int err;
894
895                 drbd_al_shrink(mdev); /* All extents inactive. */
896                 dev_info(DEV, "Writing the whole bitmap, %s\n",
897                          la_size_changed && md_moved ? "size changed and md moved" :
898                          la_size_changed ? "size changed" : "md moved");
899                 /* next line implicitly does drbd_suspend_io()+drbd_resume_io() */
900                 err = drbd_bitmap_io(mdev, &drbd_bm_write,
901                                 "size changed", BM_LOCKED_MASK);
902                 if (err) {
903                         rv = dev_size_error;
904                         goto out;
905                 }
906                 drbd_md_mark_dirty(mdev);
907         }
908
909         if (size > la_size)
910                 rv = grew;
911         if (size < la_size)
912                 rv = shrunk;
913 out:
914         lc_unlock(mdev->act_log);
915         wake_up(&mdev->al_wait);
916         drbd_resume_io(mdev);
917
918         return rv;
919 }
920
921 sector_t
922 drbd_new_dev_size(struct drbd_conf *mdev, struct drbd_backing_dev *bdev,
923                   sector_t u_size, int assume_peer_has_space)
924 {
925         sector_t p_size = mdev->p_size;   /* partner's disk size. */
926         sector_t la_size = bdev->md.la_size_sect; /* last agreed size. */
927         sector_t m_size; /* my size */
928         sector_t size = 0;
929
930         m_size = drbd_get_max_capacity(bdev);
931
932         if (mdev->state.conn < C_CONNECTED && assume_peer_has_space) {
933                 dev_warn(DEV, "Resize while not connected was forced by the user!\n");
934                 p_size = m_size;
935         }
936
937         if (p_size && m_size) {
938                 size = min_t(sector_t, p_size, m_size);
939         } else {
940                 if (la_size) {
941                         size = la_size;
942                         if (m_size && m_size < size)
943                                 size = m_size;
944                         if (p_size && p_size < size)
945                                 size = p_size;
946                 } else {
947                         if (m_size)
948                                 size = m_size;
949                         if (p_size)
950                                 size = p_size;
951                 }
952         }
953
954         if (size == 0)
955                 dev_err(DEV, "Both nodes diskless!\n");
956
957         if (u_size) {
958                 if (u_size > size)
959                         dev_err(DEV, "Requested disk size is too big (%lu > %lu)\n",
960                             (unsigned long)u_size>>1, (unsigned long)size>>1);
961                 else
962                         size = u_size;
963         }
964
965         return size;
966 }
967
968 /**
969  * drbd_check_al_size() - Ensures that the AL is of the right size
970  * @mdev:       DRBD device.
971  *
972  * Returns -EBUSY if current al lru is still used, -ENOMEM when allocation
973  * failed, and 0 on success. You should call drbd_md_sync() after you called
974  * this function.
975  */
976 static int drbd_check_al_size(struct drbd_conf *mdev, struct disk_conf *dc)
977 {
978         struct lru_cache *n, *t;
979         struct lc_element *e;
980         unsigned int in_use;
981         int i;
982
983         if (mdev->act_log &&
984             mdev->act_log->nr_elements == dc->al_extents)
985                 return 0;
986
987         in_use = 0;
988         t = mdev->act_log;
989         n = lc_create("act_log", drbd_al_ext_cache, AL_UPDATES_PER_TRANSACTION,
990                 dc->al_extents, sizeof(struct lc_element), 0);
991
992         if (n == NULL) {
993                 dev_err(DEV, "Cannot allocate act_log lru!\n");
994                 return -ENOMEM;
995         }
996         spin_lock_irq(&mdev->al_lock);
997         if (t) {
998                 for (i = 0; i < t->nr_elements; i++) {
999                         e = lc_element_by_index(t, i);
1000                         if (e->refcnt)
1001                                 dev_err(DEV, "refcnt(%d)==%d\n",
1002                                     e->lc_number, e->refcnt);
1003                         in_use += e->refcnt;
1004                 }
1005         }
1006         if (!in_use)
1007                 mdev->act_log = n;
1008         spin_unlock_irq(&mdev->al_lock);
1009         if (in_use) {
1010                 dev_err(DEV, "Activity log still in use!\n");
1011                 lc_destroy(n);
1012                 return -EBUSY;
1013         } else {
1014                 if (t)
1015                         lc_destroy(t);
1016         }
1017         drbd_md_mark_dirty(mdev); /* we changed mdev->act_log->nr_elemens */
1018         return 0;
1019 }
1020
1021 static void drbd_setup_queue_param(struct drbd_conf *mdev, unsigned int max_bio_size)
1022 {
1023         struct request_queue * const q = mdev->rq_queue;
1024         int max_hw_sectors = max_bio_size >> 9;
1025         int max_segments = 0;
1026
1027         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1028                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1029
1030                 max_hw_sectors = min(queue_max_hw_sectors(b), max_bio_size >> 9);
1031                 rcu_read_lock();
1032                 max_segments = rcu_dereference(mdev->ldev->disk_conf)->max_bio_bvecs;
1033                 rcu_read_unlock();
1034                 put_ldev(mdev);
1035         }
1036
1037         blk_queue_logical_block_size(q, 512);
1038         blk_queue_max_hw_sectors(q, max_hw_sectors);
1039         /* This is the workaround for "bio would need to, but cannot, be split" */
1040         blk_queue_max_segments(q, max_segments ? max_segments : BLK_MAX_SEGMENTS);
1041         blk_queue_segment_boundary(q, PAGE_CACHE_SIZE-1);
1042
1043         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1044                 struct request_queue * const b = mdev->ldev->backing_bdev->bd_disk->queue;
1045
1046                 blk_queue_stack_limits(q, b);
1047
1048                 if (q->backing_dev_info.ra_pages != b->backing_dev_info.ra_pages) {
1049                         dev_info(DEV, "Adjusting my ra_pages to backing device's (%lu -> %lu)\n",
1050                                  q->backing_dev_info.ra_pages,
1051                                  b->backing_dev_info.ra_pages);
1052                         q->backing_dev_info.ra_pages = b->backing_dev_info.ra_pages;
1053                 }
1054                 put_ldev(mdev);
1055         }
1056 }
1057
1058 void drbd_reconsider_max_bio_size(struct drbd_conf *mdev)
1059 {
1060         int now, new, local, peer;
1061
1062         now = queue_max_hw_sectors(mdev->rq_queue) << 9;
1063         local = mdev->local_max_bio_size; /* Eventually last known value, from volatile memory */
1064         peer = mdev->peer_max_bio_size; /* Eventually last known value, from meta data */
1065
1066         if (get_ldev_if_state(mdev, D_ATTACHING)) {
1067                 local = queue_max_hw_sectors(mdev->ldev->backing_bdev->bd_disk->queue) << 9;
1068                 mdev->local_max_bio_size = local;
1069                 put_ldev(mdev);
1070         }
1071
1072         /* We may ignore peer limits if the peer is modern enough.
1073            Because new from 8.3.8 onwards the peer can use multiple
1074            BIOs for a single peer_request */
1075         if (mdev->state.conn >= C_CONNECTED) {
1076                 if (mdev->tconn->agreed_pro_version < 94)
1077                         peer = mdev->peer_max_bio_size;
1078                 else if (mdev->tconn->agreed_pro_version == 94)
1079                         peer = DRBD_MAX_SIZE_H80_PACKET;
1080                 else /* drbd 8.3.8 onwards */
1081                         peer = DRBD_MAX_BIO_SIZE;
1082         }
1083
1084         new = min_t(int, local, peer);
1085
1086         if (mdev->state.role == R_PRIMARY && new < now)
1087                 dev_err(DEV, "ASSERT FAILED new < now; (%d < %d)\n", new, now);
1088
1089         if (new != now)
1090                 dev_info(DEV, "max BIO size = %u\n", new);
1091
1092         drbd_setup_queue_param(mdev, new);
1093 }
1094
1095 /* Starts the worker thread */
1096 static void conn_reconfig_start(struct drbd_tconn *tconn)
1097 {
1098         drbd_thread_start(&tconn->worker);
1099         conn_flush_workqueue(tconn);
1100 }
1101
1102 /* if still unconfigured, stops worker again. */
1103 static void conn_reconfig_done(struct drbd_tconn *tconn)
1104 {
1105         bool stop_threads;
1106         spin_lock_irq(&tconn->req_lock);
1107         stop_threads = conn_all_vols_unconf(tconn);
1108         spin_unlock_irq(&tconn->req_lock);
1109         if (stop_threads) {
1110                 /* asender is implicitly stopped by receiver
1111                  * in conn_disconnect() */
1112                 drbd_thread_stop(&tconn->receiver);
1113                 drbd_thread_stop(&tconn->worker);
1114         }
1115 }
1116
1117 /* Make sure IO is suspended before calling this function(). */
1118 static void drbd_suspend_al(struct drbd_conf *mdev)
1119 {
1120         int s = 0;
1121
1122         if (!lc_try_lock(mdev->act_log)) {
1123                 dev_warn(DEV, "Failed to lock al in drbd_suspend_al()\n");
1124                 return;
1125         }
1126
1127         drbd_al_shrink(mdev);
1128         spin_lock_irq(&mdev->tconn->req_lock);
1129         if (mdev->state.conn < C_CONNECTED)
1130                 s = !test_and_set_bit(AL_SUSPENDED, &mdev->flags);
1131         spin_unlock_irq(&mdev->tconn->req_lock);
1132         lc_unlock(mdev->act_log);
1133
1134         if (s)
1135                 dev_info(DEV, "Suspended AL updates\n");
1136 }
1137
1138
1139 static bool should_set_defaults(struct genl_info *info)
1140 {
1141         unsigned flags = ((struct drbd_genlmsghdr*)info->userhdr)->flags;
1142         return 0 != (flags & DRBD_GENL_F_SET_DEFAULTS);
1143 }
1144
1145 static void enforce_disk_conf_limits(struct disk_conf *dc)
1146 {
1147         if (dc->al_extents < DRBD_AL_EXTENTS_MIN)
1148                 dc->al_extents = DRBD_AL_EXTENTS_MIN;
1149         if (dc->al_extents > DRBD_AL_EXTENTS_MAX)
1150                 dc->al_extents = DRBD_AL_EXTENTS_MAX;
1151
1152         if (dc->c_plan_ahead > DRBD_C_PLAN_AHEAD_MAX)
1153                 dc->c_plan_ahead = DRBD_C_PLAN_AHEAD_MAX;
1154 }
1155
1156 int drbd_adm_disk_opts(struct sk_buff *skb, struct genl_info *info)
1157 {
1158         enum drbd_ret_code retcode;
1159         struct drbd_conf *mdev;
1160         struct disk_conf *new_disk_conf, *old_disk_conf;
1161         struct fifo_buffer *old_plan = NULL, *new_plan = NULL;
1162         int err, fifo_size;
1163
1164         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1165         if (!adm_ctx.reply_skb)
1166                 return retcode;
1167         if (retcode != NO_ERROR)
1168                 goto out;
1169
1170         mdev = adm_ctx.mdev;
1171
1172         /* we also need a disk
1173          * to change the options on */
1174         if (!get_ldev(mdev)) {
1175                 retcode = ERR_NO_DISK;
1176                 goto out;
1177         }
1178
1179         new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
1180         if (!new_disk_conf) {
1181                 retcode = ERR_NOMEM;
1182                 goto fail;
1183         }
1184
1185         mutex_lock(&mdev->tconn->conf_update);
1186         old_disk_conf = mdev->ldev->disk_conf;
1187         *new_disk_conf = *old_disk_conf;
1188         if (should_set_defaults(info))
1189                 set_disk_conf_defaults(new_disk_conf);
1190
1191         err = disk_conf_from_attrs_for_change(new_disk_conf, info);
1192         if (err && err != -ENOMSG) {
1193                 retcode = ERR_MANDATORY_TAG;
1194                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1195         }
1196
1197         if (!expect(new_disk_conf->resync_rate >= 1))
1198                 new_disk_conf->resync_rate = 1;
1199
1200         enforce_disk_conf_limits(new_disk_conf);
1201
1202         fifo_size = (new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ;
1203         if (fifo_size != mdev->rs_plan_s->size) {
1204                 new_plan = fifo_alloc(fifo_size);
1205                 if (!new_plan) {
1206                         dev_err(DEV, "kmalloc of fifo_buffer failed");
1207                         retcode = ERR_NOMEM;
1208                         goto fail_unlock;
1209                 }
1210         }
1211
1212         wait_event(mdev->al_wait, lc_try_lock(mdev->act_log));
1213         drbd_al_shrink(mdev);
1214         err = drbd_check_al_size(mdev, new_disk_conf);
1215         lc_unlock(mdev->act_log);
1216         wake_up(&mdev->al_wait);
1217
1218         if (err) {
1219                 retcode = ERR_NOMEM;
1220                 goto fail_unlock;
1221         }
1222
1223         write_lock_irq(&global_state_lock);
1224         retcode = drbd_resync_after_valid(mdev, new_disk_conf->resync_after);
1225         if (retcode == NO_ERROR) {
1226                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
1227                 drbd_resync_after_changed(mdev);
1228         }
1229         write_unlock_irq(&global_state_lock);
1230
1231         if (retcode != NO_ERROR)
1232                 goto fail_unlock;
1233
1234         if (new_plan) {
1235                 old_plan = mdev->rs_plan_s;
1236                 rcu_assign_pointer(mdev->rs_plan_s, new_plan);
1237         }
1238
1239         mutex_unlock(&mdev->tconn->conf_update);
1240         drbd_md_sync(mdev);
1241
1242         if (mdev->state.conn >= C_CONNECTED)
1243                 drbd_send_sync_param(mdev);
1244
1245         synchronize_rcu();
1246         kfree(old_disk_conf);
1247         kfree(old_plan);
1248         goto success;
1249
1250 fail_unlock:
1251         mutex_unlock(&mdev->tconn->conf_update);
1252  fail:
1253         kfree(new_disk_conf);
1254         kfree(new_plan);
1255 success:
1256         put_ldev(mdev);
1257  out:
1258         drbd_adm_finish(info, retcode);
1259         return 0;
1260 }
1261
1262 int drbd_adm_attach(struct sk_buff *skb, struct genl_info *info)
1263 {
1264         struct drbd_conf *mdev;
1265         int err;
1266         enum drbd_ret_code retcode;
1267         enum determine_dev_size dd;
1268         sector_t max_possible_sectors;
1269         sector_t min_md_device_sectors;
1270         struct drbd_backing_dev *nbc = NULL; /* new_backing_conf */
1271         struct disk_conf *new_disk_conf = NULL;
1272         struct block_device *bdev;
1273         struct lru_cache *resync_lru = NULL;
1274         struct fifo_buffer *new_plan = NULL;
1275         union drbd_state ns, os;
1276         enum drbd_state_rv rv;
1277         struct net_conf *nc;
1278         int cp_discovered = 0;
1279
1280         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1281         if (!adm_ctx.reply_skb)
1282                 return retcode;
1283         if (retcode != NO_ERROR)
1284                 goto finish;
1285
1286         mdev = adm_ctx.mdev;
1287         conn_reconfig_start(mdev->tconn);
1288
1289         /* if you want to reconfigure, please tear down first */
1290         if (mdev->state.disk > D_DISKLESS) {
1291                 retcode = ERR_DISK_CONFIGURED;
1292                 goto fail;
1293         }
1294         /* It may just now have detached because of IO error.  Make sure
1295          * drbd_ldev_destroy is done already, we may end up here very fast,
1296          * e.g. if someone calls attach from the on-io-error handler,
1297          * to realize a "hot spare" feature (not that I'd recommend that) */
1298         wait_event(mdev->misc_wait, !atomic_read(&mdev->local_cnt));
1299
1300         /* allocation not in the IO path, drbdsetup context */
1301         nbc = kzalloc(sizeof(struct drbd_backing_dev), GFP_KERNEL);
1302         if (!nbc) {
1303                 retcode = ERR_NOMEM;
1304                 goto fail;
1305         }
1306         new_disk_conf = kzalloc(sizeof(struct disk_conf), GFP_KERNEL);
1307         if (!new_disk_conf) {
1308                 retcode = ERR_NOMEM;
1309                 goto fail;
1310         }
1311         nbc->disk_conf = new_disk_conf;
1312
1313         set_disk_conf_defaults(new_disk_conf);
1314         err = disk_conf_from_attrs(new_disk_conf, info);
1315         if (err) {
1316                 retcode = ERR_MANDATORY_TAG;
1317                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1318                 goto fail;
1319         }
1320
1321         enforce_disk_conf_limits(new_disk_conf);
1322
1323         new_plan = fifo_alloc((new_disk_conf->c_plan_ahead * 10 * SLEEP_TIME) / HZ);
1324         if (!new_plan) {
1325                 retcode = ERR_NOMEM;
1326                 goto fail;
1327         }
1328
1329         if (new_disk_conf->meta_dev_idx < DRBD_MD_INDEX_FLEX_INT) {
1330                 retcode = ERR_MD_IDX_INVALID;
1331                 goto fail;
1332         }
1333
1334         rcu_read_lock();
1335         nc = rcu_dereference(mdev->tconn->net_conf);
1336         if (nc) {
1337                 if (new_disk_conf->fencing == FP_STONITH && nc->wire_protocol == DRBD_PROT_A) {
1338                         rcu_read_unlock();
1339                         retcode = ERR_STONITH_AND_PROT_A;
1340                         goto fail;
1341                 }
1342         }
1343         rcu_read_unlock();
1344
1345         bdev = blkdev_get_by_path(new_disk_conf->backing_dev,
1346                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL, mdev);
1347         if (IS_ERR(bdev)) {
1348                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->backing_dev,
1349                         PTR_ERR(bdev));
1350                 retcode = ERR_OPEN_DISK;
1351                 goto fail;
1352         }
1353         nbc->backing_bdev = bdev;
1354
1355         /*
1356          * meta_dev_idx >= 0: external fixed size, possibly multiple
1357          * drbd sharing one meta device.  TODO in that case, paranoia
1358          * check that [md_bdev, meta_dev_idx] is not yet used by some
1359          * other drbd minor!  (if you use drbd.conf + drbdadm, that
1360          * should check it for you already; but if you don't, or
1361          * someone fooled it, we need to double check here)
1362          */
1363         bdev = blkdev_get_by_path(new_disk_conf->meta_dev,
1364                                   FMODE_READ | FMODE_WRITE | FMODE_EXCL,
1365                                   (new_disk_conf->meta_dev_idx < 0) ?
1366                                   (void *)mdev : (void *)drbd_m_holder);
1367         if (IS_ERR(bdev)) {
1368                 dev_err(DEV, "open(\"%s\") failed with %ld\n", new_disk_conf->meta_dev,
1369                         PTR_ERR(bdev));
1370                 retcode = ERR_OPEN_MD_DISK;
1371                 goto fail;
1372         }
1373         nbc->md_bdev = bdev;
1374
1375         if ((nbc->backing_bdev == nbc->md_bdev) !=
1376             (new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_INTERNAL ||
1377              new_disk_conf->meta_dev_idx == DRBD_MD_INDEX_FLEX_INT)) {
1378                 retcode = ERR_MD_IDX_INVALID;
1379                 goto fail;
1380         }
1381
1382         resync_lru = lc_create("resync", drbd_bm_ext_cache,
1383                         1, 61, sizeof(struct bm_extent),
1384                         offsetof(struct bm_extent, lce));
1385         if (!resync_lru) {
1386                 retcode = ERR_NOMEM;
1387                 goto fail;
1388         }
1389
1390         /* RT - for drbd_get_max_capacity() DRBD_MD_INDEX_FLEX_INT */
1391         drbd_md_set_sector_offsets(mdev, nbc);
1392
1393         if (drbd_get_max_capacity(nbc) < new_disk_conf->disk_size) {
1394                 dev_err(DEV, "max capacity %llu smaller than disk size %llu\n",
1395                         (unsigned long long) drbd_get_max_capacity(nbc),
1396                         (unsigned long long) new_disk_conf->disk_size);
1397                 retcode = ERR_DISK_TOO_SMALL;
1398                 goto fail;
1399         }
1400
1401         if (new_disk_conf->meta_dev_idx < 0) {
1402                 max_possible_sectors = DRBD_MAX_SECTORS_FLEX;
1403                 /* at least one MB, otherwise it does not make sense */
1404                 min_md_device_sectors = (2<<10);
1405         } else {
1406                 max_possible_sectors = DRBD_MAX_SECTORS;
1407                 min_md_device_sectors = MD_RESERVED_SECT * (new_disk_conf->meta_dev_idx + 1);
1408         }
1409
1410         if (drbd_get_capacity(nbc->md_bdev) < min_md_device_sectors) {
1411                 retcode = ERR_MD_DISK_TOO_SMALL;
1412                 dev_warn(DEV, "refusing attach: md-device too small, "
1413                      "at least %llu sectors needed for this meta-disk type\n",
1414                      (unsigned long long) min_md_device_sectors);
1415                 goto fail;
1416         }
1417
1418         /* Make sure the new disk is big enough
1419          * (we may currently be R_PRIMARY with no local disk...) */
1420         if (drbd_get_max_capacity(nbc) <
1421             drbd_get_capacity(mdev->this_bdev)) {
1422                 retcode = ERR_DISK_TOO_SMALL;
1423                 goto fail;
1424         }
1425
1426         nbc->known_size = drbd_get_capacity(nbc->backing_bdev);
1427
1428         if (nbc->known_size > max_possible_sectors) {
1429                 dev_warn(DEV, "==> truncating very big lower level device "
1430                         "to currently maximum possible %llu sectors <==\n",
1431                         (unsigned long long) max_possible_sectors);
1432                 if (new_disk_conf->meta_dev_idx >= 0)
1433                         dev_warn(DEV, "==>> using internal or flexible "
1434                                       "meta data may help <<==\n");
1435         }
1436
1437         drbd_suspend_io(mdev);
1438         /* also wait for the last barrier ack. */
1439         wait_event(mdev->misc_wait, !atomic_read(&mdev->ap_pending_cnt) || drbd_suspended(mdev));
1440         /* and for any other previously queued work */
1441         drbd_flush_workqueue(mdev);
1442
1443         rv = _drbd_request_state(mdev, NS(disk, D_ATTACHING), CS_VERBOSE);
1444         retcode = rv;  /* FIXME: Type mismatch. */
1445         drbd_resume_io(mdev);
1446         if (rv < SS_SUCCESS)
1447                 goto fail;
1448
1449         if (!get_ldev_if_state(mdev, D_ATTACHING))
1450                 goto force_diskless;
1451
1452         drbd_md_set_sector_offsets(mdev, nbc);
1453
1454         if (!mdev->bitmap) {
1455                 if (drbd_bm_init(mdev)) {
1456                         retcode = ERR_NOMEM;
1457                         goto force_diskless_dec;
1458                 }
1459         }
1460
1461         retcode = drbd_md_read(mdev, nbc);
1462         if (retcode != NO_ERROR)
1463                 goto force_diskless_dec;
1464
1465         if (mdev->state.conn < C_CONNECTED &&
1466             mdev->state.role == R_PRIMARY &&
1467             (mdev->ed_uuid & ~((u64)1)) != (nbc->md.uuid[UI_CURRENT] & ~((u64)1))) {
1468                 dev_err(DEV, "Can only attach to data with current UUID=%016llX\n",
1469                     (unsigned long long)mdev->ed_uuid);
1470                 retcode = ERR_DATA_NOT_CURRENT;
1471                 goto force_diskless_dec;
1472         }
1473
1474         /* Since we are diskless, fix the activity log first... */
1475         if (drbd_check_al_size(mdev, new_disk_conf)) {
1476                 retcode = ERR_NOMEM;
1477                 goto force_diskless_dec;
1478         }
1479
1480         /* Prevent shrinking of consistent devices ! */
1481         if (drbd_md_test_flag(nbc, MDF_CONSISTENT) &&
1482             drbd_new_dev_size(mdev, nbc, nbc->disk_conf->disk_size, 0) < nbc->md.la_size_sect) {
1483                 dev_warn(DEV, "refusing to truncate a consistent device\n");
1484                 retcode = ERR_DISK_TOO_SMALL;
1485                 goto force_diskless_dec;
1486         }
1487
1488         if (!drbd_al_read_log(mdev, nbc)) {
1489                 retcode = ERR_IO_MD_DISK;
1490                 goto force_diskless_dec;
1491         }
1492
1493         /* Reset the "barriers don't work" bits here, then force meta data to
1494          * be written, to ensure we determine if barriers are supported. */
1495         if (new_disk_conf->md_flushes)
1496                 clear_bit(MD_NO_FUA, &mdev->flags);
1497         else
1498                 set_bit(MD_NO_FUA, &mdev->flags);
1499
1500         /* Point of no return reached.
1501          * Devices and memory are no longer released by error cleanup below.
1502          * now mdev takes over responsibility, and the state engine should
1503          * clean it up somewhere.  */
1504         D_ASSERT(mdev->ldev == NULL);
1505         mdev->ldev = nbc;
1506         mdev->resync = resync_lru;
1507         mdev->rs_plan_s = new_plan;
1508         nbc = NULL;
1509         resync_lru = NULL;
1510         new_disk_conf = NULL;
1511         new_plan = NULL;
1512
1513         mdev->write_ordering = WO_bdev_flush;
1514         drbd_bump_write_ordering(mdev, WO_bdev_flush);
1515
1516         if (drbd_md_test_flag(mdev->ldev, MDF_CRASHED_PRIMARY))
1517                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1518         else
1519                 clear_bit(CRASHED_PRIMARY, &mdev->flags);
1520
1521         if (drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1522             !(mdev->state.role == R_PRIMARY && mdev->tconn->susp_nod)) {
1523                 set_bit(CRASHED_PRIMARY, &mdev->flags);
1524                 cp_discovered = 1;
1525         }
1526
1527         mdev->send_cnt = 0;
1528         mdev->recv_cnt = 0;
1529         mdev->read_cnt = 0;
1530         mdev->writ_cnt = 0;
1531
1532         drbd_reconsider_max_bio_size(mdev);
1533
1534         /* If I am currently not R_PRIMARY,
1535          * but meta data primary indicator is set,
1536          * I just now recover from a hard crash,
1537          * and have been R_PRIMARY before that crash.
1538          *
1539          * Now, if I had no connection before that crash
1540          * (have been degraded R_PRIMARY), chances are that
1541          * I won't find my peer now either.
1542          *
1543          * In that case, and _only_ in that case,
1544          * we use the degr-wfc-timeout instead of the default,
1545          * so we can automatically recover from a crash of a
1546          * degraded but active "cluster" after a certain timeout.
1547          */
1548         clear_bit(USE_DEGR_WFC_T, &mdev->flags);
1549         if (mdev->state.role != R_PRIMARY &&
1550              drbd_md_test_flag(mdev->ldev, MDF_PRIMARY_IND) &&
1551             !drbd_md_test_flag(mdev->ldev, MDF_CONNECTED_IND))
1552                 set_bit(USE_DEGR_WFC_T, &mdev->flags);
1553
1554         dd = drbd_determine_dev_size(mdev, 0);
1555         if (dd == dev_size_error) {
1556                 retcode = ERR_NOMEM_BITMAP;
1557                 goto force_diskless_dec;
1558         } else if (dd == grew)
1559                 set_bit(RESYNC_AFTER_NEG, &mdev->flags);
1560
1561         if (drbd_md_test_flag(mdev->ldev, MDF_FULL_SYNC)) {
1562                 dev_info(DEV, "Assuming that all blocks are out of sync "
1563                      "(aka FullSync)\n");
1564                 if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write,
1565                         "set_n_write from attaching", BM_LOCKED_MASK)) {
1566                         retcode = ERR_IO_MD_DISK;
1567                         goto force_diskless_dec;
1568                 }
1569         } else {
1570                 if (drbd_bitmap_io(mdev, &drbd_bm_read,
1571                         "read from attaching", BM_LOCKED_MASK)) {
1572                         retcode = ERR_IO_MD_DISK;
1573                         goto force_diskless_dec;
1574                 }
1575         }
1576
1577         if (cp_discovered) {
1578                 drbd_al_apply_to_bm(mdev);
1579                 if (drbd_bitmap_io(mdev, &drbd_bm_write,
1580                         "crashed primary apply AL", BM_LOCKED_MASK)) {
1581                         retcode = ERR_IO_MD_DISK;
1582                         goto force_diskless_dec;
1583                 }
1584         }
1585
1586         if (_drbd_bm_total_weight(mdev) == drbd_bm_bits(mdev))
1587                 drbd_suspend_al(mdev); /* IO is still suspended here... */
1588
1589         spin_lock_irq(&mdev->tconn->req_lock);
1590         os = drbd_read_state(mdev);
1591         ns = os;
1592         /* If MDF_CONSISTENT is not set go into inconsistent state,
1593            otherwise investigate MDF_WasUpToDate...
1594            If MDF_WAS_UP_TO_DATE is not set go into D_OUTDATED disk state,
1595            otherwise into D_CONSISTENT state.
1596         */
1597         if (drbd_md_test_flag(mdev->ldev, MDF_CONSISTENT)) {
1598                 if (drbd_md_test_flag(mdev->ldev, MDF_WAS_UP_TO_DATE))
1599                         ns.disk = D_CONSISTENT;
1600                 else
1601                         ns.disk = D_OUTDATED;
1602         } else {
1603                 ns.disk = D_INCONSISTENT;
1604         }
1605
1606         if (drbd_md_test_flag(mdev->ldev, MDF_PEER_OUT_DATED))
1607                 ns.pdsk = D_OUTDATED;
1608
1609         rcu_read_lock();
1610         if (ns.disk == D_CONSISTENT &&
1611             (ns.pdsk == D_OUTDATED || rcu_dereference(mdev->ldev->disk_conf)->fencing == FP_DONT_CARE))
1612                 ns.disk = D_UP_TO_DATE;
1613         rcu_read_unlock();
1614
1615         /* All tests on MDF_PRIMARY_IND, MDF_CONNECTED_IND,
1616            MDF_CONSISTENT and MDF_WAS_UP_TO_DATE must happen before
1617            this point, because drbd_request_state() modifies these
1618            flags. */
1619
1620         /* In case we are C_CONNECTED postpone any decision on the new disk
1621            state after the negotiation phase. */
1622         if (mdev->state.conn == C_CONNECTED) {
1623                 mdev->new_state_tmp.i = ns.i;
1624                 ns.i = os.i;
1625                 ns.disk = D_NEGOTIATING;
1626
1627                 /* We expect to receive up-to-date UUIDs soon.
1628                    To avoid a race in receive_state, free p_uuid while
1629                    holding req_lock. I.e. atomic with the state change */
1630                 kfree(mdev->p_uuid);
1631                 mdev->p_uuid = NULL;
1632         }
1633
1634         rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
1635         spin_unlock_irq(&mdev->tconn->req_lock);
1636
1637         if (rv < SS_SUCCESS)
1638                 goto force_diskless_dec;
1639
1640         if (mdev->state.role == R_PRIMARY)
1641                 mdev->ldev->md.uuid[UI_CURRENT] |=  (u64)1;
1642         else
1643                 mdev->ldev->md.uuid[UI_CURRENT] &= ~(u64)1;
1644
1645         drbd_md_mark_dirty(mdev);
1646         drbd_md_sync(mdev);
1647
1648         kobject_uevent(&disk_to_dev(mdev->vdisk)->kobj, KOBJ_CHANGE);
1649         put_ldev(mdev);
1650         conn_reconfig_done(mdev->tconn);
1651         drbd_adm_finish(info, retcode);
1652         return 0;
1653
1654  force_diskless_dec:
1655         put_ldev(mdev);
1656  force_diskless:
1657         drbd_force_state(mdev, NS(disk, D_FAILED));
1658         drbd_md_sync(mdev);
1659  fail:
1660         conn_reconfig_done(mdev->tconn);
1661         if (nbc) {
1662                 if (nbc->backing_bdev)
1663                         blkdev_put(nbc->backing_bdev,
1664                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1665                 if (nbc->md_bdev)
1666                         blkdev_put(nbc->md_bdev,
1667                                    FMODE_READ | FMODE_WRITE | FMODE_EXCL);
1668                 kfree(nbc);
1669         }
1670         kfree(new_disk_conf);
1671         lc_destroy(resync_lru);
1672         kfree(new_plan);
1673
1674  finish:
1675         drbd_adm_finish(info, retcode);
1676         return 0;
1677 }
1678
1679 static int adm_detach(struct drbd_conf *mdev)
1680 {
1681         enum drbd_state_rv retcode;
1682         int ret;
1683         drbd_suspend_io(mdev); /* so no-one is stuck in drbd_al_begin_io */
1684         retcode = drbd_request_state(mdev, NS(disk, D_FAILED));
1685         /* D_FAILED will transition to DISKLESS. */
1686         ret = wait_event_interruptible(mdev->misc_wait,
1687                         mdev->state.disk != D_FAILED);
1688         drbd_resume_io(mdev);
1689         if ((int)retcode == (int)SS_IS_DISKLESS)
1690                 retcode = SS_NOTHING_TO_DO;
1691         if (ret)
1692                 retcode = ERR_INTR;
1693         return retcode;
1694 }
1695
1696 /* Detaching the disk is a process in multiple stages.  First we need to lock
1697  * out application IO, in-flight IO, IO stuck in drbd_al_begin_io.
1698  * Then we transition to D_DISKLESS, and wait for put_ldev() to return all
1699  * internal references as well.
1700  * Only then we have finally detached. */
1701 int drbd_adm_detach(struct sk_buff *skb, struct genl_info *info)
1702 {
1703         enum drbd_ret_code retcode;
1704
1705         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
1706         if (!adm_ctx.reply_skb)
1707                 return retcode;
1708         if (retcode != NO_ERROR)
1709                 goto out;
1710
1711         retcode = adm_detach(adm_ctx.mdev);
1712 out:
1713         drbd_adm_finish(info, retcode);
1714         return 0;
1715 }
1716
1717 static bool conn_resync_running(struct drbd_tconn *tconn)
1718 {
1719         struct drbd_conf *mdev;
1720         bool rv = false;
1721         int vnr;
1722
1723         rcu_read_lock();
1724         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1725                 if (mdev->state.conn == C_SYNC_SOURCE ||
1726                     mdev->state.conn == C_SYNC_TARGET ||
1727                     mdev->state.conn == C_PAUSED_SYNC_S ||
1728                     mdev->state.conn == C_PAUSED_SYNC_T) {
1729                         rv = true;
1730                         break;
1731                 }
1732         }
1733         rcu_read_unlock();
1734
1735         return rv;
1736 }
1737
1738 static bool conn_ov_running(struct drbd_tconn *tconn)
1739 {
1740         struct drbd_conf *mdev;
1741         bool rv = false;
1742         int vnr;
1743
1744         rcu_read_lock();
1745         idr_for_each_entry(&tconn->volumes, mdev, vnr) {
1746                 if (mdev->state.conn == C_VERIFY_S ||
1747                     mdev->state.conn == C_VERIFY_T) {
1748                         rv = true;
1749                         break;
1750                 }
1751         }
1752         rcu_read_unlock();
1753
1754         return rv;
1755 }
1756
1757 static enum drbd_ret_code
1758 _check_net_options(struct drbd_tconn *tconn, struct net_conf *old_conf, struct net_conf *new_conf)
1759 {
1760         struct drbd_conf *mdev;
1761         int i;
1762
1763         if (old_conf && tconn->cstate == C_WF_REPORT_PARAMS && tconn->agreed_pro_version < 100) {
1764                 if (new_conf->wire_protocol != old_conf->wire_protocol)
1765                         return ERR_NEED_APV_100;
1766
1767                 if (new_conf->two_primaries != old_conf->two_primaries)
1768                         return ERR_NEED_APV_100;
1769
1770                 if (!new_conf->integrity_alg != !old_conf->integrity_alg)
1771                         return ERR_NEED_APV_100;
1772
1773                 if (strcmp(new_conf->integrity_alg, old_conf->integrity_alg))
1774                         return ERR_NEED_APV_100;
1775         }
1776
1777         if (!new_conf->two_primaries &&
1778             conn_highest_role(tconn) == R_PRIMARY &&
1779             conn_highest_peer(tconn) == R_PRIMARY)
1780                 return ERR_NEED_ALLOW_TWO_PRI;
1781
1782         if (new_conf->two_primaries &&
1783             (new_conf->wire_protocol != DRBD_PROT_C))
1784                 return ERR_NOT_PROTO_C;
1785
1786         idr_for_each_entry(&tconn->volumes, mdev, i) {
1787                 if (get_ldev(mdev)) {
1788                         enum drbd_fencing_p fp = rcu_dereference(mdev->ldev->disk_conf)->fencing;
1789                         put_ldev(mdev);
1790                         if (new_conf->wire_protocol == DRBD_PROT_A && fp == FP_STONITH)
1791                                 return ERR_STONITH_AND_PROT_A;
1792                 }
1793                 if (mdev->state.role == R_PRIMARY && new_conf->discard_my_data)
1794                         return ERR_DISCARD;
1795         }
1796
1797         if (new_conf->on_congestion != OC_BLOCK && new_conf->wire_protocol != DRBD_PROT_A)
1798                 return ERR_CONG_NOT_PROTO_A;
1799
1800         return NO_ERROR;
1801 }
1802
1803 static enum drbd_ret_code
1804 check_net_options(struct drbd_tconn *tconn, struct net_conf *new_conf)
1805 {
1806         static enum drbd_ret_code rv;
1807         struct drbd_conf *mdev;
1808         int i;
1809
1810         rcu_read_lock();
1811         rv = _check_net_options(tconn, rcu_dereference(tconn->net_conf), new_conf);
1812         rcu_read_unlock();
1813
1814         /* tconn->volumes protected by genl_lock() here */
1815         idr_for_each_entry(&tconn->volumes, mdev, i) {
1816                 if (!mdev->bitmap) {
1817                         if(drbd_bm_init(mdev))
1818                                 return ERR_NOMEM;
1819                 }
1820         }
1821
1822         return rv;
1823 }
1824
1825 struct crypto {
1826         struct crypto_hash *verify_tfm;
1827         struct crypto_hash *csums_tfm;
1828         struct crypto_hash *cram_hmac_tfm;
1829         struct crypto_hash *integrity_tfm;
1830         void *int_dig_in;
1831         void *int_dig_vv;
1832 };
1833
1834 static int
1835 alloc_hash(struct crypto_hash **tfm, char *tfm_name, int err_alg)
1836 {
1837         if (!tfm_name[0])
1838                 return NO_ERROR;
1839
1840         *tfm = crypto_alloc_hash(tfm_name, 0, CRYPTO_ALG_ASYNC);
1841         if (IS_ERR(*tfm)) {
1842                 *tfm = NULL;
1843                 return err_alg;
1844         }
1845
1846         return NO_ERROR;
1847 }
1848
1849 static enum drbd_ret_code
1850 alloc_crypto(struct crypto *crypto, struct net_conf *new_conf)
1851 {
1852         char hmac_name[CRYPTO_MAX_ALG_NAME];
1853         enum drbd_ret_code rv;
1854         int hash_size;
1855
1856         rv = alloc_hash(&crypto->csums_tfm, new_conf->csums_alg,
1857                        ERR_CSUMS_ALG);
1858         if (rv != NO_ERROR)
1859                 return rv;
1860         rv = alloc_hash(&crypto->verify_tfm, new_conf->verify_alg,
1861                        ERR_VERIFY_ALG);
1862         if (rv != NO_ERROR)
1863                 return rv;
1864         rv = alloc_hash(&crypto->integrity_tfm, new_conf->integrity_alg,
1865                        ERR_INTEGRITY_ALG);
1866         if (rv != NO_ERROR)
1867                 return rv;
1868         if (new_conf->cram_hmac_alg[0] != 0) {
1869                 snprintf(hmac_name, CRYPTO_MAX_ALG_NAME, "hmac(%s)",
1870                          new_conf->cram_hmac_alg);
1871
1872                 rv = alloc_hash(&crypto->cram_hmac_tfm, hmac_name,
1873                                ERR_AUTH_ALG);
1874         }
1875         if (crypto->integrity_tfm) {
1876                 hash_size = crypto_hash_digestsize(crypto->integrity_tfm);
1877                 crypto->int_dig_in = kmalloc(hash_size, GFP_KERNEL);
1878                 if (!crypto->int_dig_in)
1879                         return ERR_NOMEM;
1880                 crypto->int_dig_vv = kmalloc(hash_size, GFP_KERNEL);
1881                 if (!crypto->int_dig_vv)
1882                         return ERR_NOMEM;
1883         }
1884
1885         return rv;
1886 }
1887
1888 static void free_crypto(struct crypto *crypto)
1889 {
1890         kfree(crypto->int_dig_in);
1891         kfree(crypto->int_dig_vv);
1892         crypto_free_hash(crypto->cram_hmac_tfm);
1893         crypto_free_hash(crypto->integrity_tfm);
1894         crypto_free_hash(crypto->csums_tfm);
1895         crypto_free_hash(crypto->verify_tfm);
1896 }
1897
1898 int drbd_adm_net_opts(struct sk_buff *skb, struct genl_info *info)
1899 {
1900         enum drbd_ret_code retcode;
1901         struct drbd_tconn *tconn;
1902         struct net_conf *old_conf, *new_conf = NULL;
1903         int err;
1904         int ovr; /* online verify running */
1905         int rsr; /* re-sync running */
1906         struct crypto crypto = { };
1907
1908         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONNECTION);
1909         if (!adm_ctx.reply_skb)
1910                 return retcode;
1911         if (retcode != NO_ERROR)
1912                 goto out;
1913
1914         tconn = adm_ctx.tconn;
1915
1916         new_conf = kzalloc(sizeof(struct net_conf), GFP_KERNEL);
1917         if (!new_conf) {
1918                 retcode = ERR_NOMEM;
1919                 goto out;
1920         }
1921
1922         conn_reconfig_start(tconn);
1923
1924         mutex_lock(&tconn->data.mutex);
1925         mutex_lock(&tconn->conf_update);
1926         old_conf = tconn->net_conf;
1927
1928         if (!old_conf) {
1929                 drbd_msg_put_info("net conf missing, try connect");
1930                 retcode = ERR_INVALID_REQUEST;
1931                 goto fail;
1932         }
1933
1934         *new_conf = *old_conf;
1935         if (should_set_defaults(info))
1936                 set_net_conf_defaults(new_conf);
1937
1938         err = net_conf_from_attrs_for_change(new_conf, info);
1939         if (err && err != -ENOMSG) {
1940                 retcode = ERR_MANDATORY_TAG;
1941                 drbd_msg_put_info(from_attrs_err_to_txt(err));
1942                 goto fail;
1943         }
1944
1945         retcode = check_net_options(tconn, new_conf);
1946         if (retcode != NO_ERROR)
1947                 goto fail;
1948
1949         /* re-sync running */
1950         rsr = conn_resync_running(tconn);
1951         if (rsr && strcmp(new_conf->csums_alg, old_conf->csums_alg)) {
1952                 retcode = ERR_CSUMS_RESYNC_RUNNING;
1953                 goto fail;
1954         }
1955
1956         /* online verify running */
1957         ovr = conn_ov_running(tconn);
1958         if (ovr && strcmp(new_conf->verify_alg, old_conf->verify_alg)) {
1959                 retcode = ERR_VERIFY_RUNNING;
1960                 goto fail;
1961         }
1962
1963         retcode = alloc_crypto(&crypto, new_conf);
1964         if (retcode != NO_ERROR)
1965                 goto fail;
1966
1967         rcu_assign_pointer(tconn->net_conf, new_conf);
1968
1969         if (!rsr) {
1970                 crypto_free_hash(tconn->csums_tfm);
1971                 tconn->csums_tfm = crypto.csums_tfm;
1972                 crypto.csums_tfm = NULL;
1973         }
1974         if (!ovr) {
1975                 crypto_free_hash(tconn->verify_tfm);
1976                 tconn->verify_tfm = crypto.verify_tfm;
1977                 crypto.verify_tfm = NULL;
1978         }
1979
1980         kfree(tconn->int_dig_in);
1981         tconn->int_dig_in = crypto.int_dig_in;
1982         kfree(tconn->int_dig_vv);
1983         tconn->int_dig_vv = crypto.int_dig_vv;
1984         crypto_free_hash(tconn->integrity_tfm);
1985         tconn->integrity_tfm = crypto.integrity_tfm;
1986         if (tconn->cstate >= C_WF_REPORT_PARAMS && tconn->agreed_pro_version >= 100)
1987                 /* Do this without trying to take tconn->data.mutex again.  */
1988                 __drbd_send_protocol(tconn, P_PROTOCOL_UPDATE);
1989
1990         crypto_free_hash(tconn->cram_hmac_tfm);
1991         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
1992
1993         mutex_unlock(&tconn->conf_update);
1994         mutex_unlock(&tconn->data.mutex);
1995         synchronize_rcu();
1996         kfree(old_conf);
1997
1998         if (tconn->cstate >= C_WF_REPORT_PARAMS)
1999                 drbd_send_sync_param(minor_to_mdev(conn_lowest_minor(tconn)));
2000
2001         goto done;
2002
2003  fail:
2004         mutex_unlock(&tconn->conf_update);
2005         mutex_unlock(&tconn->data.mutex);
2006         free_crypto(&crypto);
2007         kfree(new_conf);
2008  done:
2009         conn_reconfig_done(tconn);
2010  out:
2011         drbd_adm_finish(info, retcode);
2012         return 0;
2013 }
2014
2015 int drbd_adm_connect(struct sk_buff *skb, struct genl_info *info)
2016 {
2017         struct drbd_conf *mdev;
2018         struct net_conf *old_conf, *new_conf = NULL;
2019         struct crypto crypto = { };
2020         struct drbd_tconn *tconn;
2021         enum drbd_ret_code retcode;
2022         int i;
2023         int err;
2024
2025         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
2026
2027         if (!adm_ctx.reply_skb)
2028                 return retcode;
2029         if (retcode != NO_ERROR)
2030                 goto out;
2031         if (!(adm_ctx.my_addr && adm_ctx.peer_addr)) {
2032                 drbd_msg_put_info("connection endpoint(s) missing");
2033                 retcode = ERR_INVALID_REQUEST;
2034                 goto out;
2035         }
2036
2037         /* No need for _rcu here. All reconfiguration is
2038          * strictly serialized on genl_lock(). We are protected against
2039          * concurrent reconfiguration/addition/deletion */
2040         list_for_each_entry(tconn, &drbd_tconns, all_tconn) {
2041                 if (nla_len(adm_ctx.my_addr) == tconn->my_addr_len &&
2042                     !memcmp(nla_data(adm_ctx.my_addr), &tconn->my_addr, tconn->my_addr_len)) {
2043                         retcode = ERR_LOCAL_ADDR;
2044                         goto out;
2045                 }
2046
2047                 if (nla_len(adm_ctx.peer_addr) == tconn->peer_addr_len &&
2048                     !memcmp(nla_data(adm_ctx.peer_addr), &tconn->peer_addr, tconn->peer_addr_len)) {
2049                         retcode = ERR_PEER_ADDR;
2050                         goto out;
2051                 }
2052         }
2053
2054         tconn = adm_ctx.tconn;
2055         conn_reconfig_start(tconn);
2056
2057         if (tconn->cstate > C_STANDALONE) {
2058                 retcode = ERR_NET_CONFIGURED;
2059                 goto fail;
2060         }
2061
2062         /* allocation not in the IO path, cqueue thread context */
2063         new_conf = kzalloc(sizeof(*new_conf), GFP_KERNEL);
2064         if (!new_conf) {
2065                 retcode = ERR_NOMEM;
2066                 goto fail;
2067         }
2068
2069         set_net_conf_defaults(new_conf);
2070
2071         err = net_conf_from_attrs(new_conf, info);
2072         if (err) {
2073                 retcode = ERR_MANDATORY_TAG;
2074                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2075                 goto fail;
2076         }
2077
2078         retcode = check_net_options(tconn, new_conf);
2079         if (retcode != NO_ERROR)
2080                 goto fail;
2081
2082         retcode = alloc_crypto(&crypto, new_conf);
2083         if (retcode != NO_ERROR)
2084                 goto fail;
2085
2086         ((char *)new_conf->shared_secret)[SHARED_SECRET_MAX-1] = 0;
2087
2088         conn_flush_workqueue(tconn);
2089
2090         mutex_lock(&tconn->conf_update);
2091         old_conf = tconn->net_conf;
2092         if (old_conf) {
2093                 retcode = ERR_NET_CONFIGURED;
2094                 mutex_unlock(&tconn->conf_update);
2095                 goto fail;
2096         }
2097         rcu_assign_pointer(tconn->net_conf, new_conf);
2098
2099         conn_free_crypto(tconn);
2100         tconn->int_dig_in = crypto.int_dig_in;
2101         tconn->int_dig_vv = crypto.int_dig_vv;
2102         tconn->cram_hmac_tfm = crypto.cram_hmac_tfm;
2103         tconn->integrity_tfm = crypto.integrity_tfm;
2104         tconn->csums_tfm = crypto.csums_tfm;
2105         tconn->verify_tfm = crypto.verify_tfm;
2106
2107         tconn->my_addr_len = nla_len(adm_ctx.my_addr);
2108         memcpy(&tconn->my_addr, nla_data(adm_ctx.my_addr), tconn->my_addr_len);
2109         tconn->peer_addr_len = nla_len(adm_ctx.peer_addr);
2110         memcpy(&tconn->peer_addr, nla_data(adm_ctx.peer_addr), tconn->peer_addr_len);
2111
2112         mutex_unlock(&tconn->conf_update);
2113
2114         rcu_read_lock();
2115         idr_for_each_entry(&tconn->volumes, mdev, i) {
2116                 mdev->send_cnt = 0;
2117                 mdev->recv_cnt = 0;
2118         }
2119         rcu_read_unlock();
2120
2121         retcode = conn_request_state(tconn, NS(conn, C_UNCONNECTED), CS_VERBOSE);
2122
2123         conn_reconfig_done(tconn);
2124         drbd_adm_finish(info, retcode);
2125         return 0;
2126
2127 fail:
2128         free_crypto(&crypto);
2129         kfree(new_conf);
2130
2131         conn_reconfig_done(tconn);
2132 out:
2133         drbd_adm_finish(info, retcode);
2134         return 0;
2135 }
2136
2137 static enum drbd_state_rv conn_try_disconnect(struct drbd_tconn *tconn, bool force)
2138 {
2139         enum drbd_state_rv rv;
2140
2141         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2142                         force ? CS_HARD : 0);
2143
2144         switch (rv) {
2145         case SS_NOTHING_TO_DO:
2146                 break;
2147         case SS_ALREADY_STANDALONE:
2148                 return SS_SUCCESS;
2149         case SS_PRIMARY_NOP:
2150                 /* Our state checking code wants to see the peer outdated. */
2151                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2152                                                 pdsk, D_OUTDATED), CS_VERBOSE);
2153                 break;
2154         case SS_CW_FAILED_BY_PEER:
2155                 /* The peer probably wants to see us outdated. */
2156                 rv = conn_request_state(tconn, NS2(conn, C_DISCONNECTING,
2157                                                         disk, D_OUTDATED), 0);
2158                 if (rv == SS_IS_DISKLESS || rv == SS_LOWER_THAN_OUTDATED) {
2159                         rv = conn_request_state(tconn, NS(conn, C_DISCONNECTING),
2160                                         CS_HARD);
2161                 }
2162                 break;
2163         default:;
2164                 /* no special handling necessary */
2165         }
2166
2167         if (rv >= SS_SUCCESS) {
2168                 enum drbd_state_rv rv2;
2169                 /* No one else can reconfigure the network while I am here.
2170                  * The state handling only uses drbd_thread_stop_nowait(),
2171                  * we want to really wait here until the receiver is no more.
2172                  */
2173                 drbd_thread_stop(&adm_ctx.tconn->receiver);
2174
2175                 /* Race breaker.  This additional state change request may be
2176                  * necessary, if this was a forced disconnect during a receiver
2177                  * restart.  We may have "killed" the receiver thread just
2178                  * after drbdd_init() returned.  Typically, we should be
2179                  * C_STANDALONE already, now, and this becomes a no-op.
2180                  */
2181                 rv2 = conn_request_state(tconn, NS(conn, C_STANDALONE),
2182                                 CS_VERBOSE | CS_HARD);
2183                 if (rv2 < SS_SUCCESS)
2184                         conn_err(tconn,
2185                                 "unexpected rv2=%d in conn_try_disconnect()\n",
2186                                 rv2);
2187         }
2188         return rv;
2189 }
2190
2191 int drbd_adm_disconnect(struct sk_buff *skb, struct genl_info *info)
2192 {
2193         struct disconnect_parms parms;
2194         struct drbd_tconn *tconn;
2195         enum drbd_state_rv rv;
2196         enum drbd_ret_code retcode;
2197         int err;
2198
2199         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_CONNECTION);
2200         if (!adm_ctx.reply_skb)
2201                 return retcode;
2202         if (retcode != NO_ERROR)
2203                 goto fail;
2204
2205         tconn = adm_ctx.tconn;
2206         memset(&parms, 0, sizeof(parms));
2207         if (info->attrs[DRBD_NLA_DISCONNECT_PARMS]) {
2208                 err = disconnect_parms_from_attrs(&parms, info);
2209                 if (err) {
2210                         retcode = ERR_MANDATORY_TAG;
2211                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2212                         goto fail;
2213                 }
2214         }
2215
2216         rv = conn_try_disconnect(tconn, parms.force_disconnect);
2217         if (rv < SS_SUCCESS)
2218                 retcode = rv;  /* FIXME: Type mismatch. */
2219         else
2220                 retcode = NO_ERROR;
2221  fail:
2222         drbd_adm_finish(info, retcode);
2223         return 0;
2224 }
2225
2226 void resync_after_online_grow(struct drbd_conf *mdev)
2227 {
2228         int iass; /* I am sync source */
2229
2230         dev_info(DEV, "Resync of new storage after online grow\n");
2231         if (mdev->state.role != mdev->state.peer)
2232                 iass = (mdev->state.role == R_PRIMARY);
2233         else
2234                 iass = test_bit(DISCARD_CONCURRENT, &mdev->tconn->flags);
2235
2236         if (iass)
2237                 drbd_start_resync(mdev, C_SYNC_SOURCE);
2238         else
2239                 _drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE + CS_SERIALIZE);
2240 }
2241
2242 int drbd_adm_resize(struct sk_buff *skb, struct genl_info *info)
2243 {
2244         struct disk_conf *old_disk_conf, *new_disk_conf = NULL;
2245         struct resize_parms rs;
2246         struct drbd_conf *mdev;
2247         enum drbd_ret_code retcode;
2248         enum determine_dev_size dd;
2249         enum dds_flags ddsf;
2250         sector_t u_size;
2251         int err;
2252
2253         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2254         if (!adm_ctx.reply_skb)
2255                 return retcode;
2256         if (retcode != NO_ERROR)
2257                 goto fail;
2258
2259         memset(&rs, 0, sizeof(struct resize_parms));
2260         if (info->attrs[DRBD_NLA_RESIZE_PARMS]) {
2261                 err = resize_parms_from_attrs(&rs, info);
2262                 if (err) {
2263                         retcode = ERR_MANDATORY_TAG;
2264                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2265                         goto fail;
2266                 }
2267         }
2268
2269         mdev = adm_ctx.mdev;
2270         if (mdev->state.conn > C_CONNECTED) {
2271                 retcode = ERR_RESIZE_RESYNC;
2272                 goto fail;
2273         }
2274
2275         if (mdev->state.role == R_SECONDARY &&
2276             mdev->state.peer == R_SECONDARY) {
2277                 retcode = ERR_NO_PRIMARY;
2278                 goto fail;
2279         }
2280
2281         if (!get_ldev(mdev)) {
2282                 retcode = ERR_NO_DISK;
2283                 goto fail;
2284         }
2285
2286         if (rs.no_resync && mdev->tconn->agreed_pro_version < 93) {
2287                 retcode = ERR_NEED_APV_93;
2288                 goto fail;
2289         }
2290
2291         rcu_read_lock();
2292         u_size = rcu_dereference(mdev->ldev->disk_conf)->disk_size;
2293         rcu_read_unlock();
2294         if (u_size != (sector_t)rs.resize_size) {
2295                 new_disk_conf = kmalloc(sizeof(struct disk_conf), GFP_KERNEL);
2296                 if (!new_disk_conf) {
2297                         retcode = ERR_NOMEM;
2298                         goto fail;
2299                 }
2300         }
2301
2302         if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev))
2303                 mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
2304
2305         if (new_disk_conf) {
2306                 mutex_lock(&mdev->tconn->conf_update);
2307                 old_disk_conf = mdev->ldev->disk_conf;
2308                 *new_disk_conf = *old_disk_conf;
2309                 new_disk_conf->disk_size = (sector_t)rs.resize_size;
2310                 rcu_assign_pointer(mdev->ldev->disk_conf, new_disk_conf);
2311                 mutex_unlock(&mdev->tconn->conf_update);
2312                 synchronize_rcu();
2313                 kfree(old_disk_conf);
2314         }
2315
2316         ddsf = (rs.resize_force ? DDSF_FORCED : 0) | (rs.no_resync ? DDSF_NO_RESYNC : 0);
2317         dd = drbd_determine_dev_size(mdev, ddsf);
2318         drbd_md_sync(mdev);
2319         put_ldev(mdev);
2320         if (dd == dev_size_error) {
2321                 retcode = ERR_NOMEM_BITMAP;
2322                 goto fail;
2323         }
2324
2325         if (mdev->state.conn == C_CONNECTED) {
2326                 if (dd == grew)
2327                         set_bit(RESIZE_PENDING, &mdev->flags);
2328
2329                 drbd_send_uuids(mdev);
2330                 drbd_send_sizes(mdev, 1, ddsf);
2331         }
2332
2333  fail:
2334         drbd_adm_finish(info, retcode);
2335         return 0;
2336 }
2337
2338 void drbd_set_res_opts_defaults(struct res_opts *r)
2339 {
2340         return set_res_opts_defaults(r);
2341 }
2342
2343 int drbd_adm_resource_opts(struct sk_buff *skb, struct genl_info *info)
2344 {
2345         enum drbd_ret_code retcode;
2346         cpumask_var_t new_cpu_mask;
2347         struct drbd_tconn *tconn;
2348         struct res_opts res_opts;
2349         int err;
2350
2351         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
2352         if (!adm_ctx.reply_skb)
2353                 return retcode;
2354         if (retcode != NO_ERROR)
2355                 goto fail;
2356         tconn = adm_ctx.tconn;
2357
2358         if (!zalloc_cpumask_var(&new_cpu_mask, GFP_KERNEL)) {
2359                 retcode = ERR_NOMEM;
2360                 drbd_msg_put_info("unable to allocate cpumask");
2361                 goto fail;
2362         }
2363
2364         res_opts = tconn->res_opts;
2365         if (should_set_defaults(info))
2366                 set_res_opts_defaults(&res_opts);
2367
2368         err = res_opts_from_attrs(&res_opts, info);
2369         if (err && err != -ENOMSG) {
2370                 retcode = ERR_MANDATORY_TAG;
2371                 drbd_msg_put_info(from_attrs_err_to_txt(err));
2372                 goto fail;
2373         }
2374
2375         /* silently ignore cpu mask on UP kernel */
2376         if (nr_cpu_ids > 1 && res_opts.cpu_mask[0] != 0) {
2377                 err = __bitmap_parse(res_opts.cpu_mask, 32, 0,
2378                                 cpumask_bits(new_cpu_mask), nr_cpu_ids);
2379                 if (err) {
2380                         conn_warn(tconn, "__bitmap_parse() failed with %d\n", err);
2381                         retcode = ERR_CPU_MASK_PARSE;
2382                         goto fail;
2383                 }
2384         }
2385
2386
2387         tconn->res_opts = res_opts;
2388
2389         if (!cpumask_equal(tconn->cpu_mask, new_cpu_mask)) {
2390                 cpumask_copy(tconn->cpu_mask, new_cpu_mask);
2391                 drbd_calc_cpu_mask(tconn);
2392                 tconn->receiver.reset_cpu_mask = 1;
2393                 tconn->asender.reset_cpu_mask = 1;
2394                 tconn->worker.reset_cpu_mask = 1;
2395         }
2396
2397 fail:
2398         free_cpumask_var(new_cpu_mask);
2399
2400         drbd_adm_finish(info, retcode);
2401         return 0;
2402 }
2403
2404 int drbd_adm_invalidate(struct sk_buff *skb, struct genl_info *info)
2405 {
2406         struct drbd_conf *mdev;
2407         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2408
2409         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2410         if (!adm_ctx.reply_skb)
2411                 return retcode;
2412         if (retcode != NO_ERROR)
2413                 goto out;
2414
2415         mdev = adm_ctx.mdev;
2416
2417         /* If there is still bitmap IO pending, probably because of a previous
2418          * resync just being finished, wait for it before requesting a new resync. */
2419         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2420
2421         retcode = _drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T), CS_ORDERED);
2422
2423         if (retcode < SS_SUCCESS && retcode != SS_NEED_CONNECTION)
2424                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2425
2426         while (retcode == SS_NEED_CONNECTION) {
2427                 spin_lock_irq(&mdev->tconn->req_lock);
2428                 if (mdev->state.conn < C_CONNECTED)
2429                         retcode = _drbd_set_state(_NS(mdev, disk, D_INCONSISTENT), CS_VERBOSE, NULL);
2430                 spin_unlock_irq(&mdev->tconn->req_lock);
2431
2432                 if (retcode != SS_NEED_CONNECTION)
2433                         break;
2434
2435                 retcode = drbd_request_state(mdev, NS(conn, C_STARTING_SYNC_T));
2436         }
2437
2438 out:
2439         drbd_adm_finish(info, retcode);
2440         return 0;
2441 }
2442
2443 static int drbd_bmio_set_susp_al(struct drbd_conf *mdev)
2444 {
2445         int rv;
2446
2447         rv = drbd_bmio_set_n_write(mdev);
2448         drbd_suspend_al(mdev);
2449         return rv;
2450 }
2451
2452 static int drbd_adm_simple_request_state(struct sk_buff *skb, struct genl_info *info,
2453                 union drbd_state mask, union drbd_state val)
2454 {
2455         enum drbd_ret_code retcode;
2456
2457         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2458         if (!adm_ctx.reply_skb)
2459                 return retcode;
2460         if (retcode != NO_ERROR)
2461                 goto out;
2462
2463         retcode = drbd_request_state(adm_ctx.mdev, mask, val);
2464 out:
2465         drbd_adm_finish(info, retcode);
2466         return 0;
2467 }
2468
2469 int drbd_adm_invalidate_peer(struct sk_buff *skb, struct genl_info *info)
2470 {
2471         return drbd_adm_simple_request_state(skb, info, NS(conn, C_STARTING_SYNC_S));
2472 }
2473
2474 int drbd_adm_pause_sync(struct sk_buff *skb, struct genl_info *info)
2475 {
2476         enum drbd_ret_code retcode;
2477
2478         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2479         if (!adm_ctx.reply_skb)
2480                 return retcode;
2481         if (retcode != NO_ERROR)
2482                 goto out;
2483
2484         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 1)) == SS_NOTHING_TO_DO)
2485                 retcode = ERR_PAUSE_IS_SET;
2486 out:
2487         drbd_adm_finish(info, retcode);
2488         return 0;
2489 }
2490
2491 int drbd_adm_resume_sync(struct sk_buff *skb, struct genl_info *info)
2492 {
2493         union drbd_dev_state s;
2494         enum drbd_ret_code retcode;
2495
2496         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2497         if (!adm_ctx.reply_skb)
2498                 return retcode;
2499         if (retcode != NO_ERROR)
2500                 goto out;
2501
2502         if (drbd_request_state(adm_ctx.mdev, NS(user_isp, 0)) == SS_NOTHING_TO_DO) {
2503                 s = adm_ctx.mdev->state;
2504                 if (s.conn == C_PAUSED_SYNC_S || s.conn == C_PAUSED_SYNC_T) {
2505                         retcode = s.aftr_isp ? ERR_PIC_AFTER_DEP :
2506                                   s.peer_isp ? ERR_PIC_PEER_DEP : ERR_PAUSE_IS_CLEAR;
2507                 } else {
2508                         retcode = ERR_PAUSE_IS_CLEAR;
2509                 }
2510         }
2511
2512 out:
2513         drbd_adm_finish(info, retcode);
2514         return 0;
2515 }
2516
2517 int drbd_adm_suspend_io(struct sk_buff *skb, struct genl_info *info)
2518 {
2519         return drbd_adm_simple_request_state(skb, info, NS(susp, 1));
2520 }
2521
2522 int drbd_adm_resume_io(struct sk_buff *skb, struct genl_info *info)
2523 {
2524         struct drbd_conf *mdev;
2525         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
2526
2527         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2528         if (!adm_ctx.reply_skb)
2529                 return retcode;
2530         if (retcode != NO_ERROR)
2531                 goto out;
2532
2533         mdev = adm_ctx.mdev;
2534         if (test_bit(NEW_CUR_UUID, &mdev->flags)) {
2535                 drbd_uuid_new_current(mdev);
2536                 clear_bit(NEW_CUR_UUID, &mdev->flags);
2537         }
2538         drbd_suspend_io(mdev);
2539         retcode = drbd_request_state(mdev, NS3(susp, 0, susp_nod, 0, susp_fen, 0));
2540         if (retcode == SS_SUCCESS) {
2541                 if (mdev->state.conn < C_CONNECTED)
2542                         tl_clear(mdev->tconn);
2543                 if (mdev->state.disk == D_DISKLESS || mdev->state.disk == D_FAILED)
2544                         tl_restart(mdev->tconn, FAIL_FROZEN_DISK_IO);
2545         }
2546         drbd_resume_io(mdev);
2547
2548 out:
2549         drbd_adm_finish(info, retcode);
2550         return 0;
2551 }
2552
2553 int drbd_adm_outdate(struct sk_buff *skb, struct genl_info *info)
2554 {
2555         return drbd_adm_simple_request_state(skb, info, NS(disk, D_OUTDATED));
2556 }
2557
2558 int nla_put_drbd_cfg_context(struct sk_buff *skb, struct drbd_tconn *tconn, unsigned vnr)
2559 {
2560         struct nlattr *nla;
2561         nla = nla_nest_start(skb, DRBD_NLA_CFG_CONTEXT);
2562         if (!nla)
2563                 goto nla_put_failure;
2564         if (vnr != VOLUME_UNSPECIFIED)
2565                 NLA_PUT_U32(skb, T_ctx_volume, vnr);
2566         NLA_PUT_STRING(skb, T_ctx_resource_name, tconn->name);
2567         if (tconn->my_addr_len)
2568                 NLA_PUT(skb, T_ctx_my_addr, tconn->my_addr_len, &tconn->my_addr);
2569         if (tconn->peer_addr_len)
2570                 NLA_PUT(skb, T_ctx_peer_addr, tconn->peer_addr_len, &tconn->peer_addr);
2571         nla_nest_end(skb, nla);
2572         return 0;
2573
2574 nla_put_failure:
2575         if (nla)
2576                 nla_nest_cancel(skb, nla);
2577         return -EMSGSIZE;
2578 }
2579
2580 int nla_put_status_info(struct sk_buff *skb, struct drbd_conf *mdev,
2581                 const struct sib_info *sib)
2582 {
2583         struct state_info *si = NULL; /* for sizeof(si->member); */
2584         struct net_conf *nc;
2585         struct nlattr *nla;
2586         int got_ldev;
2587         int err = 0;
2588         int exclude_sensitive;
2589
2590         /* If sib != NULL, this is drbd_bcast_event, which anyone can listen
2591          * to.  So we better exclude_sensitive information.
2592          *
2593          * If sib == NULL, this is drbd_adm_get_status, executed synchronously
2594          * in the context of the requesting user process. Exclude sensitive
2595          * information, unless current has superuser.
2596          *
2597          * NOTE: for drbd_adm_get_status_all(), this is a netlink dump, and
2598          * relies on the current implementation of netlink_dump(), which
2599          * executes the dump callback successively from netlink_recvmsg(),
2600          * always in the context of the receiving process */
2601         exclude_sensitive = sib || !capable(CAP_SYS_ADMIN);
2602
2603         got_ldev = get_ldev(mdev);
2604
2605         /* We need to add connection name and volume number information still.
2606          * Minor number is in drbd_genlmsghdr. */
2607         if (nla_put_drbd_cfg_context(skb, mdev->tconn, mdev->vnr))
2608                 goto nla_put_failure;
2609
2610         if (res_opts_to_skb(skb, &mdev->tconn->res_opts, exclude_sensitive))
2611                 goto nla_put_failure;
2612
2613         rcu_read_lock();
2614         if (got_ldev)
2615                 if (disk_conf_to_skb(skb, rcu_dereference(mdev->ldev->disk_conf), exclude_sensitive))
2616                         goto nla_put_failure;
2617
2618         nc = rcu_dereference(mdev->tconn->net_conf);
2619         if (nc)
2620                 err = net_conf_to_skb(skb, nc, exclude_sensitive);
2621         rcu_read_unlock();
2622         if (err)
2623                 goto nla_put_failure;
2624
2625         nla = nla_nest_start(skb, DRBD_NLA_STATE_INFO);
2626         if (!nla)
2627                 goto nla_put_failure;
2628         NLA_PUT_U32(skb, T_sib_reason, sib ? sib->sib_reason : SIB_GET_STATUS_REPLY);
2629         NLA_PUT_U32(skb, T_current_state, mdev->state.i);
2630         NLA_PUT_U64(skb, T_ed_uuid, mdev->ed_uuid);
2631         NLA_PUT_U64(skb, T_capacity, drbd_get_capacity(mdev->this_bdev));
2632
2633         if (got_ldev) {
2634                 NLA_PUT_U32(skb, T_disk_flags, mdev->ldev->md.flags);
2635                 NLA_PUT(skb, T_uuids, sizeof(si->uuids), mdev->ldev->md.uuid);
2636                 NLA_PUT_U64(skb, T_bits_total, drbd_bm_bits(mdev));
2637                 NLA_PUT_U64(skb, T_bits_oos, drbd_bm_total_weight(mdev));
2638                 if (C_SYNC_SOURCE <= mdev->state.conn &&
2639                     C_PAUSED_SYNC_T >= mdev->state.conn) {
2640                         NLA_PUT_U64(skb, T_bits_rs_total, mdev->rs_total);
2641                         NLA_PUT_U64(skb, T_bits_rs_failed, mdev->rs_failed);
2642                 }
2643         }
2644
2645         if (sib) {
2646                 switch(sib->sib_reason) {
2647                 case SIB_SYNC_PROGRESS:
2648                 case SIB_GET_STATUS_REPLY:
2649                         break;
2650                 case SIB_STATE_CHANGE:
2651                         NLA_PUT_U32(skb, T_prev_state, sib->os.i);
2652                         NLA_PUT_U32(skb, T_new_state, sib->ns.i);
2653                         break;
2654                 case SIB_HELPER_POST:
2655                         NLA_PUT_U32(skb,
2656                                 T_helper_exit_code, sib->helper_exit_code);
2657                         /* fall through */
2658                 case SIB_HELPER_PRE:
2659                         NLA_PUT_STRING(skb, T_helper, sib->helper_name);
2660                         break;
2661                 }
2662         }
2663         nla_nest_end(skb, nla);
2664
2665         if (0)
2666 nla_put_failure:
2667                 err = -EMSGSIZE;
2668         if (got_ldev)
2669                 put_ldev(mdev);
2670         return err;
2671 }
2672
2673 int drbd_adm_get_status(struct sk_buff *skb, struct genl_info *info)
2674 {
2675         enum drbd_ret_code retcode;
2676         int err;
2677
2678         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2679         if (!adm_ctx.reply_skb)
2680                 return retcode;
2681         if (retcode != NO_ERROR)
2682                 goto out;
2683
2684         err = nla_put_status_info(adm_ctx.reply_skb, adm_ctx.mdev, NULL);
2685         if (err) {
2686                 nlmsg_free(adm_ctx.reply_skb);
2687                 return err;
2688         }
2689 out:
2690         drbd_adm_finish(info, retcode);
2691         return 0;
2692 }
2693
2694 int get_one_status(struct sk_buff *skb, struct netlink_callback *cb)
2695 {
2696         struct drbd_conf *mdev;
2697         struct drbd_genlmsghdr *dh;
2698         struct drbd_tconn *pos = (struct drbd_tconn*)cb->args[0];
2699         struct drbd_tconn *tconn = NULL;
2700         struct drbd_tconn *tmp;
2701         unsigned volume = cb->args[1];
2702
2703         /* Open coded, deferred, iteration:
2704          * list_for_each_entry_safe(tconn, tmp, &drbd_tconns, all_tconn) {
2705          *      idr_for_each_entry(&tconn->volumes, mdev, i) {
2706          *        ...
2707          *      }
2708          * }
2709          * where tconn is cb->args[0];
2710          * and i is cb->args[1];
2711          *
2712          * cb->args[2] indicates if we shall loop over all resources,
2713          * or just dump all volumes of a single resource.
2714          *
2715          * This may miss entries inserted after this dump started,
2716          * or entries deleted before they are reached.
2717          *
2718          * We need to make sure the mdev won't disappear while
2719          * we are looking at it, and revalidate our iterators
2720          * on each iteration.
2721          */
2722
2723         /* synchronize with conn_create()/conn_destroy() */
2724         rcu_read_lock();
2725         /* revalidate iterator position */
2726         list_for_each_entry_rcu(tmp, &drbd_tconns, all_tconn) {
2727                 if (pos == NULL) {
2728                         /* first iteration */
2729                         pos = tmp;
2730                         tconn = pos;
2731                         break;
2732                 }
2733                 if (tmp == pos) {
2734                         tconn = pos;
2735                         break;
2736                 }
2737         }
2738         if (tconn) {
2739 next_tconn:
2740                 mdev = idr_get_next(&tconn->volumes, &volume);
2741                 if (!mdev) {
2742                         /* No more volumes to dump on this tconn.
2743                          * Advance tconn iterator. */
2744                         pos = list_entry_rcu(tconn->all_tconn.next,
2745                                              struct drbd_tconn, all_tconn);
2746                         /* Did we dump any volume on this tconn yet? */
2747                         if (volume != 0) {
2748                                 /* If we reached the end of the list,
2749                                  * or only a single resource dump was requested,
2750                                  * we are done. */
2751                                 if (&pos->all_tconn == &drbd_tconns || cb->args[2])
2752                                         goto out;
2753                                 volume = 0;
2754                                 tconn = pos;
2755                                 goto next_tconn;
2756                         }
2757                 }
2758
2759                 dh = genlmsg_put(skb, NETLINK_CB(cb->skb).pid,
2760                                 cb->nlh->nlmsg_seq, &drbd_genl_family,
2761                                 NLM_F_MULTI, DRBD_ADM_GET_STATUS);
2762                 if (!dh)
2763                         goto out;
2764
2765                 if (!mdev) {
2766                         /* this is a tconn without a single volume */
2767                         dh->minor = -1U;
2768                         dh->ret_code = NO_ERROR;
2769                         if (nla_put_drbd_cfg_context(skb, tconn, VOLUME_UNSPECIFIED))
2770                                 genlmsg_cancel(skb, dh);
2771                         else
2772                                 genlmsg_end(skb, dh);
2773                         goto out;
2774                 }
2775
2776                 D_ASSERT(mdev->vnr == volume);
2777                 D_ASSERT(mdev->tconn == tconn);
2778
2779                 dh->minor = mdev_to_minor(mdev);
2780                 dh->ret_code = NO_ERROR;
2781
2782                 if (nla_put_status_info(skb, mdev, NULL)) {
2783                         genlmsg_cancel(skb, dh);
2784                         goto out;
2785                 }
2786                 genlmsg_end(skb, dh);
2787         }
2788
2789 out:
2790         rcu_read_unlock();
2791         /* where to start the next iteration */
2792         cb->args[0] = (long)pos;
2793         cb->args[1] = (pos == tconn) ? volume + 1 : 0;
2794
2795         /* No more tconns/volumes/minors found results in an empty skb.
2796          * Which will terminate the dump. */
2797         return skb->len;
2798 }
2799
2800 /*
2801  * Request status of all resources, or of all volumes within a single resource.
2802  *
2803  * This is a dump, as the answer may not fit in a single reply skb otherwise.
2804  * Which means we cannot use the family->attrbuf or other such members, because
2805  * dump is NOT protected by the genl_lock().  During dump, we only have access
2806  * to the incoming skb, and need to opencode "parsing" of the nlattr payload.
2807  *
2808  * Once things are setup properly, we call into get_one_status().
2809  */
2810 int drbd_adm_get_status_all(struct sk_buff *skb, struct netlink_callback *cb)
2811 {
2812         const unsigned hdrlen = GENL_HDRLEN + GENL_MAGIC_FAMILY_HDRSZ;
2813         struct nlattr *nla;
2814         const char *resource_name;
2815         struct drbd_tconn *tconn;
2816         int maxtype;
2817
2818         /* Is this a followup call? */
2819         if (cb->args[0]) {
2820                 /* ... of a single resource dump,
2821                  * and the resource iterator has been advanced already? */
2822                 if (cb->args[2] && cb->args[2] != cb->args[0])
2823                         return 0; /* DONE. */
2824                 goto dump;
2825         }
2826
2827         /* First call (from netlink_dump_start).  We need to figure out
2828          * which resource(s) the user wants us to dump. */
2829         nla = nla_find(nlmsg_attrdata(cb->nlh, hdrlen),
2830                         nlmsg_attrlen(cb->nlh, hdrlen),
2831                         DRBD_NLA_CFG_CONTEXT);
2832
2833         /* No explicit context given.  Dump all. */
2834         if (!nla)
2835                 goto dump;
2836         maxtype = ARRAY_SIZE(drbd_cfg_context_nl_policy) - 1;
2837         nla = drbd_nla_find_nested(maxtype, nla, __nla_type(T_ctx_resource_name));
2838         if (IS_ERR(nla))
2839                 return PTR_ERR(nla);
2840         /* context given, but no name present? */
2841         if (!nla)
2842                 return -EINVAL;
2843         resource_name = nla_data(nla);
2844         tconn = conn_get_by_name(resource_name);
2845
2846         if (!tconn)
2847                 return -ENODEV;
2848
2849         kref_put(&tconn->kref, &conn_destroy); /* get_one_status() (re)validates tconn by itself */
2850
2851         /* prime iterators, and set "filter" mode mark:
2852          * only dump this tconn. */
2853         cb->args[0] = (long)tconn;
2854         /* cb->args[1] = 0; passed in this way. */
2855         cb->args[2] = (long)tconn;
2856
2857 dump:
2858         return get_one_status(skb, cb);
2859 }
2860
2861 int drbd_adm_get_timeout_type(struct sk_buff *skb, struct genl_info *info)
2862 {
2863         enum drbd_ret_code retcode;
2864         struct timeout_parms tp;
2865         int err;
2866
2867         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2868         if (!adm_ctx.reply_skb)
2869                 return retcode;
2870         if (retcode != NO_ERROR)
2871                 goto out;
2872
2873         tp.timeout_type =
2874                 adm_ctx.mdev->state.pdsk == D_OUTDATED ? UT_PEER_OUTDATED :
2875                 test_bit(USE_DEGR_WFC_T, &adm_ctx.mdev->flags) ? UT_DEGRADED :
2876                 UT_DEFAULT;
2877
2878         err = timeout_parms_to_priv_skb(adm_ctx.reply_skb, &tp);
2879         if (err) {
2880                 nlmsg_free(adm_ctx.reply_skb);
2881                 return err;
2882         }
2883 out:
2884         drbd_adm_finish(info, retcode);
2885         return 0;
2886 }
2887
2888 int drbd_adm_start_ov(struct sk_buff *skb, struct genl_info *info)
2889 {
2890         struct drbd_conf *mdev;
2891         enum drbd_ret_code retcode;
2892
2893         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2894         if (!adm_ctx.reply_skb)
2895                 return retcode;
2896         if (retcode != NO_ERROR)
2897                 goto out;
2898
2899         mdev = adm_ctx.mdev;
2900         if (info->attrs[DRBD_NLA_START_OV_PARMS]) {
2901                 /* resume from last known position, if possible */
2902                 struct start_ov_parms parms =
2903                         { .ov_start_sector = mdev->ov_start_sector };
2904                 int err = start_ov_parms_from_attrs(&parms, info);
2905                 if (err) {
2906                         retcode = ERR_MANDATORY_TAG;
2907                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2908                         goto out;
2909                 }
2910                 /* w_make_ov_request expects position to be aligned */
2911                 mdev->ov_start_sector = parms.ov_start_sector & ~BM_SECT_PER_BIT;
2912         }
2913         /* If there is still bitmap IO pending, e.g. previous resync or verify
2914          * just being finished, wait for it before requesting a new resync. */
2915         wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
2916         retcode = drbd_request_state(mdev,NS(conn,C_VERIFY_S));
2917 out:
2918         drbd_adm_finish(info, retcode);
2919         return 0;
2920 }
2921
2922
2923 int drbd_adm_new_c_uuid(struct sk_buff *skb, struct genl_info *info)
2924 {
2925         struct drbd_conf *mdev;
2926         enum drbd_ret_code retcode;
2927         int skip_initial_sync = 0;
2928         int err;
2929         struct new_c_uuid_parms args;
2930
2931         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
2932         if (!adm_ctx.reply_skb)
2933                 return retcode;
2934         if (retcode != NO_ERROR)
2935                 goto out_nolock;
2936
2937         mdev = adm_ctx.mdev;
2938         memset(&args, 0, sizeof(args));
2939         if (info->attrs[DRBD_NLA_NEW_C_UUID_PARMS]) {
2940                 err = new_c_uuid_parms_from_attrs(&args, info);
2941                 if (err) {
2942                         retcode = ERR_MANDATORY_TAG;
2943                         drbd_msg_put_info(from_attrs_err_to_txt(err));
2944                         goto out_nolock;
2945                 }
2946         }
2947
2948         mutex_lock(mdev->state_mutex); /* Protects us against serialized state changes. */
2949
2950         if (!get_ldev(mdev)) {
2951                 retcode = ERR_NO_DISK;
2952                 goto out;
2953         }
2954
2955         /* this is "skip initial sync", assume to be clean */
2956         if (mdev->state.conn == C_CONNECTED && mdev->tconn->agreed_pro_version >= 90 &&
2957             mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED && args.clear_bm) {
2958                 dev_info(DEV, "Preparing to skip initial sync\n");
2959                 skip_initial_sync = 1;
2960         } else if (mdev->state.conn != C_STANDALONE) {
2961                 retcode = ERR_CONNECTED;
2962                 goto out_dec;
2963         }
2964
2965         drbd_uuid_set(mdev, UI_BITMAP, 0); /* Rotate UI_BITMAP to History 1, etc... */
2966         drbd_uuid_new_current(mdev); /* New current, previous to UI_BITMAP */
2967
2968         if (args.clear_bm) {
2969                 err = drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write,
2970                         "clear_n_write from new_c_uuid", BM_LOCKED_MASK);
2971                 if (err) {
2972                         dev_err(DEV, "Writing bitmap failed with %d\n",err);
2973                         retcode = ERR_IO_MD_DISK;
2974                 }
2975                 if (skip_initial_sync) {
2976                         drbd_send_uuids_skip_initial_sync(mdev);
2977                         _drbd_uuid_set(mdev, UI_BITMAP, 0);
2978                         drbd_print_uuids(mdev, "cleared bitmap UUID");
2979                         spin_lock_irq(&mdev->tconn->req_lock);
2980                         _drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
2981                                         CS_VERBOSE, NULL);
2982                         spin_unlock_irq(&mdev->tconn->req_lock);
2983                 }
2984         }
2985
2986         drbd_md_sync(mdev);
2987 out_dec:
2988         put_ldev(mdev);
2989 out:
2990         mutex_unlock(mdev->state_mutex);
2991 out_nolock:
2992         drbd_adm_finish(info, retcode);
2993         return 0;
2994 }
2995
2996 static enum drbd_ret_code
2997 drbd_check_resource_name(const char *name)
2998 {
2999         if (!name || !name[0]) {
3000                 drbd_msg_put_info("resource name missing");
3001                 return ERR_MANDATORY_TAG;
3002         }
3003         /* if we want to use these in sysfs/configfs/debugfs some day,
3004          * we must not allow slashes */
3005         if (strchr(name, '/')) {
3006                 drbd_msg_put_info("invalid resource name");
3007                 return ERR_INVALID_REQUEST;
3008         }
3009         return NO_ERROR;
3010 }
3011
3012 int drbd_adm_new_resource(struct sk_buff *skb, struct genl_info *info)
3013 {
3014         enum drbd_ret_code retcode;
3015
3016         retcode = drbd_adm_prepare(skb, info, 0);
3017         if (!adm_ctx.reply_skb)
3018                 return retcode;
3019         if (retcode != NO_ERROR)
3020                 goto out;
3021
3022         retcode = drbd_check_resource_name(adm_ctx.resource_name);
3023         if (retcode != NO_ERROR)
3024                 goto out;
3025
3026         if (adm_ctx.tconn) {
3027                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL) {
3028                         retcode = ERR_INVALID_REQUEST;
3029                         drbd_msg_put_info("resource exists");
3030                 }
3031                 /* else: still NO_ERROR */
3032                 goto out;
3033         }
3034
3035         if (!conn_create(adm_ctx.resource_name))
3036                 retcode = ERR_NOMEM;
3037 out:
3038         drbd_adm_finish(info, retcode);
3039         return 0;
3040 }
3041
3042 int drbd_adm_add_minor(struct sk_buff *skb, struct genl_info *info)
3043 {
3044         struct drbd_genlmsghdr *dh = info->userhdr;
3045         enum drbd_ret_code retcode;
3046
3047         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
3048         if (!adm_ctx.reply_skb)
3049                 return retcode;
3050         if (retcode != NO_ERROR)
3051                 goto out;
3052
3053         /* FIXME drop minor_count parameter, limit to MINORMASK */
3054         if (dh->minor >= minor_count) {
3055                 drbd_msg_put_info("requested minor out of range");
3056                 retcode = ERR_INVALID_REQUEST;
3057                 goto out;
3058         }
3059         if (adm_ctx.volume > DRBD_VOLUME_MAX) {
3060                 drbd_msg_put_info("requested volume id out of range");
3061                 retcode = ERR_INVALID_REQUEST;
3062                 goto out;
3063         }
3064
3065         /* drbd_adm_prepare made sure already
3066          * that mdev->tconn and mdev->vnr match the request. */
3067         if (adm_ctx.mdev) {
3068                 if (info->nlhdr->nlmsg_flags & NLM_F_EXCL)
3069                         retcode = ERR_MINOR_EXISTS;
3070                 /* else: still NO_ERROR */
3071                 goto out;
3072         }
3073
3074         retcode = conn_new_minor(adm_ctx.tconn, dh->minor, adm_ctx.volume);
3075 out:
3076         drbd_adm_finish(info, retcode);
3077         return 0;
3078 }
3079
3080 static enum drbd_ret_code adm_delete_minor(struct drbd_conf *mdev)
3081 {
3082         if (mdev->state.disk == D_DISKLESS &&
3083             /* no need to be mdev->state.conn == C_STANDALONE &&
3084              * we may want to delete a minor from a live replication group.
3085              */
3086             mdev->state.role == R_SECONDARY) {
3087                 idr_remove(&mdev->tconn->volumes, mdev->vnr);
3088                 idr_remove(&minors, mdev_to_minor(mdev));
3089                 del_gendisk(mdev->vdisk);
3090                 synchronize_rcu();
3091                 kref_put(&mdev->kref, &drbd_minor_destroy);
3092                 return NO_ERROR;
3093         } else
3094                 return ERR_MINOR_CONFIGURED;
3095 }
3096
3097 int drbd_adm_delete_minor(struct sk_buff *skb, struct genl_info *info)
3098 {
3099         enum drbd_ret_code retcode;
3100
3101         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_MINOR);
3102         if (!adm_ctx.reply_skb)
3103                 return retcode;
3104         if (retcode != NO_ERROR)
3105                 goto out;
3106
3107         retcode = adm_delete_minor(adm_ctx.mdev);
3108 out:
3109         drbd_adm_finish(info, retcode);
3110         return 0;
3111 }
3112
3113 int drbd_adm_down(struct sk_buff *skb, struct genl_info *info)
3114 {
3115         int retcode; /* enum drbd_ret_code rsp. enum drbd_state_rv */
3116         struct drbd_conf *mdev;
3117         unsigned i;
3118
3119         retcode = drbd_adm_prepare(skb, info, 0);
3120         if (!adm_ctx.reply_skb)
3121                 return retcode;
3122         if (retcode != NO_ERROR)
3123                 goto out;
3124
3125         if (!adm_ctx.tconn) {
3126                 retcode = ERR_RES_NOT_KNOWN;
3127                 goto out;
3128         }
3129
3130         /* demote */
3131         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3132                 retcode = drbd_set_role(mdev, R_SECONDARY, 0);
3133                 if (retcode < SS_SUCCESS) {
3134                         drbd_msg_put_info("failed to demote");
3135                         goto out;
3136                 }
3137         }
3138
3139         retcode = conn_try_disconnect(adm_ctx.tconn, 0);
3140         if (retcode < SS_SUCCESS) {
3141                 drbd_msg_put_info("failed to disconnect");
3142                 goto out;
3143         }
3144
3145         /* detach */
3146         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3147                 retcode = adm_detach(mdev);
3148                 if (retcode < SS_SUCCESS) {
3149                         drbd_msg_put_info("failed to detach");
3150                         goto out;
3151                 }
3152         }
3153
3154         /* If we reach this, all volumes (of this tconn) are Secondary,
3155          * Disconnected, Diskless, aka Unconfigured. Make sure all threads have
3156          * actually stopped, state handling only does drbd_thread_stop_nowait(). */
3157         drbd_thread_stop(&adm_ctx.tconn->worker);
3158
3159         /* Now, nothing can fail anymore */
3160
3161         /* delete volumes */
3162         idr_for_each_entry(&adm_ctx.tconn->volumes, mdev, i) {
3163                 retcode = adm_delete_minor(mdev);
3164                 if (retcode != NO_ERROR) {
3165                         /* "can not happen" */
3166                         drbd_msg_put_info("failed to delete volume");
3167                         goto out;
3168                 }
3169         }
3170
3171         /* delete connection */
3172         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3173                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3174                 synchronize_rcu();
3175                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3176
3177                 retcode = NO_ERROR;
3178         } else {
3179                 /* "can not happen" */
3180                 retcode = ERR_RES_IN_USE;
3181                 drbd_msg_put_info("failed to delete connection");
3182         }
3183         goto out;
3184 out:
3185         drbd_adm_finish(info, retcode);
3186         return 0;
3187 }
3188
3189 int drbd_adm_del_resource(struct sk_buff *skb, struct genl_info *info)
3190 {
3191         enum drbd_ret_code retcode;
3192
3193         retcode = drbd_adm_prepare(skb, info, DRBD_ADM_NEED_RESOURCE);
3194         if (!adm_ctx.reply_skb)
3195                 return retcode;
3196         if (retcode != NO_ERROR)
3197                 goto out;
3198
3199         if (conn_lowest_minor(adm_ctx.tconn) < 0) {
3200                 list_del_rcu(&adm_ctx.tconn->all_tconn);
3201                 synchronize_rcu();
3202                 kref_put(&adm_ctx.tconn->kref, &conn_destroy);
3203
3204                 retcode = NO_ERROR;
3205         } else {
3206                 retcode = ERR_RES_IN_USE;
3207         }
3208
3209         if (retcode == NO_ERROR)
3210                 drbd_thread_stop(&adm_ctx.tconn->worker);
3211 out:
3212         drbd_adm_finish(info, retcode);
3213         return 0;
3214 }
3215
3216 void drbd_bcast_event(struct drbd_conf *mdev, const struct sib_info *sib)
3217 {
3218         static atomic_t drbd_genl_seq = ATOMIC_INIT(2); /* two. */
3219         struct sk_buff *msg;
3220         struct drbd_genlmsghdr *d_out;
3221         unsigned seq;
3222         int err = -ENOMEM;
3223
3224         seq = atomic_inc_return(&drbd_genl_seq);
3225         msg = genlmsg_new(NLMSG_GOODSIZE, GFP_NOIO);
3226         if (!msg)
3227                 goto failed;
3228
3229         err = -EMSGSIZE;
3230         d_out = genlmsg_put(msg, 0, seq, &drbd_genl_family, 0, DRBD_EVENT);
3231         if (!d_out) /* cannot happen, but anyways. */
3232                 goto nla_put_failure;
3233         d_out->minor = mdev_to_minor(mdev);
3234         d_out->ret_code = NO_ERROR;
3235
3236         if (nla_put_status_info(msg, mdev, sib))
3237                 goto nla_put_failure;
3238         genlmsg_end(msg, d_out);
3239         err = drbd_genl_multicast_events(msg, 0);
3240         /* msg has been consumed or freed in netlink_broadcast() */
3241         if (err && err != -ESRCH)
3242                 goto failed;
3243
3244         return;
3245
3246 nla_put_failure:
3247         nlmsg_free(msg);
3248 failed:
3249         dev_err(DEV, "Error %d while broadcasting event. "
3250                         "Event seq:%u sib_reason:%u\n",
3251                         err, seq, sib->sib_reason);
3252 }